DextrousDave
DextrousDave

Reputation: 6793

Calculating Viewport dimensions and displaying it dynamically with Jquery

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

Upvotes: 0

Views: 1484

Answers (1)

Esailija
Esailija

Reputation: 140230

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:

$(document).ready(function() {
    $(window).resize(function() {
        $('#viewport').empty().append($(window).width(), "x", $(window).height())
    }).resize(); //Initial call
});

demo: http://jsfiddle.net/3Lbb7/2/

Upvotes: 6

Related Questions