简体   繁体   中英

Capture first visible div id while scrolling (viewport)

I have this page:

在此处输入图片说明

I want to capture on which div I am while I'm scrolling.

I know If I use:

if( $(document).scrollTop() > $('#div1').position().top) {  
console.log('Div1')
  }

...it will capture the div1 but instead of using this code for every div I want to set 1 snippet for all divs

Something like:

var a =   // The div i am at
if( $(document).scrollTop() > $(a).position().top) {    
    console.log($(a).attr('id'))
}

I am looking something like the viewport: http://www.appelsiini.net/projects/viewport/3x2.html

Can I achieve that without a plugin, simply 2-3 lines?

Here's a nice way to do it. You may want to optimize the '<=' with a pixel offset to improve user experience and move the div selector ($divs) outside the callback to increase performance. Have a look at my fiddle: http://jsfiddle.net/brentmn/CmpEt/

$(window).scroll(function() {

    var winTop = $(this).scrollTop();
    var $divs = $('div');

    var top = $.grep($divs, function(item) {
        return $(item).position().top <= winTop;
    });
});
   $(window).scroll(function () {

        $("#privacyContent div").each(function () {
            var bottomOffset = ($(this).offset().top + $(this).height());
            console.log("Botom=",bottomOffset ,"Win= ", $(window).scrollTop());
            if (bottomOffset > $(window).scrollTop()) {

                $("#menu a").removeClass("active");
              //  console.log("Div is= ",$(this).attr('id'));
                $("#menu a[href='#" + $(this).attr('id') + "']").addClass("active");
                $(".b").removeClass("fsActive");
                var div = $(this);
                div.find(".b").addClass("fsActive");

                return false;
            }
        });

});

I do it like this it works fine it detect all div id

Just throw it into a loop.

var list = [];
$("div").each(function(index) {
    if( $(document).scrollTop() > $(this).position().top) 
        list.push($(this));
});

alert(list);

The list will than have every div that is within your viewport.

I'd suggest using the jQuery Inview plugin:

https://github.com/protonet/jquery.inview

Well maintained Plugin that detects whatever content is in the viewer currently, enabling you to bind functions to an inview event. So as soon as your div is in view you could fire off all the relevant functions you wanted and then again when it has left the users view. Would be great for your needs.

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