w3resource

JavaScript: Get the width and height of a window online

JavaScript DOM: Exercise-13 with Solution

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.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript program to highlight the bold words of the following paragraph, on mouse over a certain link.
Next: Javascript Drawing Exercises Home.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-dom-exercise-13.php