Add Div With Dynamic VergeJS Viewport Values To HTML
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:
- A function named
getVergeValues
- Two jquery calls on window resize and document ready where you call your function
In your function you have 4 parts:
- The calcul of sizes with verge
- The construction of your elements
- The setting of the text in your elements
- 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 append
ing, 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"