Display live width and height when resizing a window
In html head:
<script type="text/javascript">
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth; myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
}
</script>
In html body:
<script type="text/javascript">
document.write('<p>' + myWidth + 'x' + myHeight + '</p>');
</script>
It works well. The question is: how can I display width / height values when resizing the browser? Like here http://quirktools.com/screenfly/ in the lower left corner.
Many thanks!
Snap to window.onresize. Do not use document.write(). Put <p>in your HTML and give it an identifier. Then just set the innerHTML of the element directly:
window.onresize = displayWindowSize;
window.onload = displayWindowSize;
function displayWindowSize() {
// your size calculation code here
document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
};
I like the gilly3 solution, but it would be helpful to have the full code (for those in a hurry!)
<script>
window.onresize = displayWindowSize;
window.onload = displayWindowSize;
function displayWindowSize() {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
// your size calculation code here
document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
};
</script>
Or, if you are already using jquery, you can use the resize event to capture the event and without any parameters to trigger the start event when the window loads..resize(handler).resize()
Like this:
$(window).resize(function() {
// your size calculation code here
$("#dimensions").html(myWidth);
}).resize();