Skip to content Skip to sidebar Skip to footer

Add Div With Dynamic VergeJS Viewport Values To HTML

Using Verge.js during development to display current viewport width and height cross-browser. https://jsfiddle.net/ccL30a26/ function getVergeValues() { viewportWidth = verge.vie

Solution 1:

I don't know lab.js, but in your attemp there is a mistake in the javascript you tried.

function getVergeValues() {
   viewportWidth  = verge.viewportW() // Get the viewport width in pixels.
   viewportHeight = verge.viewportH() // Get the viewport height in pixels.

   var $width  = $( "<div class='w'></div>" );
   var $height = $( "<div class='h'></div>" );

   $('.w').text(viewportWidth  + 'px wide');
   $('.h').text(viewportHeight + 'px high');

   $( "body" ).append( $width, $height);
}

$(window).on('resize', getVergeValues);
$(document).ready(getVergeValues);

In this code snippet you have two parts:

  1. A function named getVergeValues
  2. Two jquery calls on window resize and document ready where you call your function

In your function you have 4 parts:

  1. The calcul of sizes with verge
  2. The construction of your elements
  3. The setting of the text in your elements
  4. The add of your elements in your page

Actually the items 2 and 4 have to be done only once as you don't want to add those elements again anf again.

The items 1 and 3 have to be repeted on each resize as in your first jsfiddle.

So putting the elements 2 and 4 out of the function make your code behave the way you want: https://jsfiddle.net/zfzq1crL/.

If you want to keep those element in a function you can make a function called only on document ready: https://jsfiddle.net/tfqsjf2t/.

You still have to call your function in the init function in order to have the sizes in your elements at the start.


Solution 2:

Because you are appending, the old values don't get cleared. To achieve what you want, you should set html of width and height divs that already exist in body. So you should not create w and h divs each time the function is called. Instead, you should change their html.

HTML:

<body>
    ...Your body content..
    <div class="w"></div>
    <div class="h"></div>
</body>

JS:

function getVergeValues() {

    viewportWidth  = verge.viewportW() // Get the viewport width in pixels.
    viewportHeight = verge.viewportH() // Get the viewport height in pixels.

    $('.w').html(viewportWidth  + 'px wide');
    $('.h').html(viewportHeight + 'px high');    
}

$(window).on('resize', getVergeValues);

Also, you should call getVergeValues function on document load to fill the values initially.

$(document).on('ready', function(){
    getVergeValues();
}

Post a Comment for "Add Div With Dynamic VergeJS Viewport Values To HTML"