JavaScript: Get the width and height of a window online

JavaScript DOM: Exercise-13 with Solution

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

Sample Solution: -

HTML Code:

<!DOCTYPE html>
<meta charset=utf-8 />
<title>Window Size : height and width</title>
<!-- Resize the window (here output panel) and see the result !-->
<body onload="getSize()" onresize="getSize()">
<div id="wh"> 
<!-- Place height and width size here! --> 

JavaScript Code:

function getSize()
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
// put the result into a h1 tag
 document.getElementById('wh').innerHTML = "<h1>Width: " + w + " • Height: " + h + "</h1>";

Sample output:



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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

eval() function

const sum = eval('10*10+5');

eval evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is 10 * 10 + 5. This returns the number 105.

Ref: https://bit.ly/323Y0P6