I have this functions to calculate the viewport width and height dynamically as the browser window size changes. Now I want to display that values on screen, but it does not work. Any ideas?
JS:
<script type="text/javascript">
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
$('viewport').html(viewportWidth);
$('viewport').html(viewportHeight);
$(window).resize(function() {
$('viewport').html(viewportWidth);
$('viewport').html(viewportHeight);
});
</script>
HTML:
<div id="viewport">width and height should be displayed here dynamically</div>
Thank you
Issues:
You are using
.html, which overwrites the previous html of the element. You could use.append.You are using the variables you only initially set, rather than fetching new values when the window resizes.
You are using
"viewport", it should be"#viewport"You should also make sure the elements exist when your code runs, which means dom ready handler or putting the script element after the elements
Try this:
demo: http://jsfiddle.net/3Lbb7/2/