w3resource

JavaScript: Get the width and height of a window online

JavaScript DOM: Exercise-13 with Solution

Window Resize Dimensions

Write a JavaScript program to get the window width and height (any time the window is resized).

Sample Solution:

HTML Code:

<!-- Declaration of HTML document type -->
<!DOCTYPE html>
<!-- Start of HTML document -->
<html>
<!-- Start of head section -->
<head>
<!-- Declaring character encoding -->
<meta charset=utf-8 />
<!-- Setting title of the document -->
<title>Window Size : height and width</title>
<!-- End of head section -->
</head>
<!-- Comment indicating to resize the window and see the result -->
<!-- Resize the window (here output panel) and see the result !-->
<!-- Start of body section with onload and onresize events -->
<body onload="getSize()" onresize="getSize()">
<!-- Division to display height and width size -->
<div id="wh"> 
    <!-- Place height and width size here! --> 
</div>
<!-- End of body section -->
<body>
</body>
<!-- End of HTML document -->
</html>

JavaScript Code:

// Function declaration for getSize
function getSize()
{
    // Getting the width of the viewport
    var w = document.documentElement.clientWidth;
    // Getting the height of the viewport
    var h = document.documentElement.clientHeight;
        
    // Put the result into a h1 tag
    document.getElementById('wh').innerHTML = "<h1>Width: " + w + " • Height: " + h + "</h1>";
}

output:

javascript-dom-exercise-13.

Flowchart:

Flowchart: JavaScript - Get the width and height of a window online.

Live Demo:

See the Pen javascript-dom-exercise-13 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that continuously displays the current window width and height in real time as the window is resized.
  • Write a JavaScript function that updates a dedicated paragraph with the new window dimensions each time the window is resized.
  • Write a JavaScript function that throttles the window resize event to update the dimensions only every 500ms.
  • Write a JavaScript function that logs the window dimensions to the console every time a resize event occurs, ensuring performance optimization.

Go to:


PREV : Highlight Bold on Hover.
NEXT : Javascript Drawing Exercises Home.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.