ryanve / verge

get viewport dimensions...detect elements in the viewport...trust in <!DOCTYPE html>
https://ryanve.dev/verge
MIT License
695 stars 51 forks source link

Add div with dynamic VergeJS viewport values to HTML #23

Closed ghost closed 7 years ago

ghost commented 7 years ago

Trying to display a div with the Verge values during development. Please see https://jsfiddle.net/ccL30a26/1/.

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);

However now on domready there is no value shown and on window resize the values get added up filling the viewport.

How can I get the initial value to show on domready and only the current value to show on window resize please?

I assume this is not really an issue but am wondering why Verge does not display the inital value on domready. Do you have a clue?

Additionally it would be great if you could help with letting me know how I can avoid filling the viewport with new divs as I resize. Thank you.

ryanve commented 7 years ago

It's because you're appending each time you call getVergeValues. You only need to append once. After that you can just update. Try more like:

function update() {
    $('.w').text(verge.viewportW()  + 'px wide');
    $('.h').text(verge.viewportH() + 'px high');
}

$('body').append('<div class=w></div><div class=h></div>');
$(window).on('resize', update);
$(document).ready(update);
ghost commented 7 years ago

Thank you.