简体   繁体   中英

How to do something everytime a certain element is in view using jQuery?

Right now every time the user reaches the bottom of my page I update the url hash using this code:

var new_page_value = 1;
$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        new_page_value += 1;
        window.location.hash = 'page-' + new_page_value;
    }
});

How can I do the same when the user scrolls past any of the divs with the class "page" in the code below? For example if the user scrolls into view the 1st one the hash should be updated to #page-1 but as soon as they scroll into view the 2nd one the hash should be updated to #page-2 and so on. And if they scroll back to the first the hash should once again be updated to #page-1. Basically the hash should update based on whatever div is in view.

<div class="page" data-page-num="1"></div>

<br /><br /><br /><br /><br /><br /><br /><br /><br />

<div class="page" data-page-num="2"></div>

<br /><br /><br /><br /><br /><br /><br /><br /><br />

<div class="page" data-page-num="3"></div>

This code may help, but it might be a little intensive on the client side.

var new_page_value = 1;
$(window).scroll(function() {
    $(".page").each(function() {
        var position = $(this).position();
        if($(window).scrollTop() == position.top) {
            new_page_value += 1;
            window.location.hash = 'page-' + new_page_value;
        }
    });

    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        new_page_value += 1;
        window.location.hash = 'page-' + new_page_value;
    }
});

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