简体   繁体   中英

Check if element is in viewport

I have this code which works fine to understand if an element is inside the viewport. I would like to write to the console once when it is in the viewport and once when it is not (and not continuously as it does now).

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on('resize scroll', function() {
    if ($('#Something').isInViewport()) {
        console.log('in viewport');
    } else {
        console.log('not in viewport');
    }
});

edit: thanks, i tried your code and it works fine but i can't fit it to my context with multiple elements

var sur = document.getElementsByClassName("survey");


    let wasInViewPort;
    $(window).on('resize scroll', function() {
      for (var i = 0; i < sur.length; i++) {
        const isInViewPort = $(sur[i]).isInViewport();
        if (isInViewPort !== wasInViewPort) {
          var a = isInViewPort ? ' in viewport' : ' not in viewport';
            console.log(sur[i].id+a);
        }
        wasInViewPort = isInViewPort;
      }
    
    
    });

Just use a variable to keep track of the last result, and only call console.log when that changes:

let wasInViewPort;
$(window).on('resize scroll', function() {
    const isInViewPort = $('#Something').isInViewport();
    if (isInViewPort !== wasInViewPort) {
        console.log(`{isInViewPort ? '' : 'not '}in viewport`);
    }
    wasInViewPort = isInViewPort;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM