Skip to content Skip to sidebar Skip to footer

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') }

Solution 1:

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

Solution 2:

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.

Solution 3:

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.

Solution 4:

   $(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");

                returnfalse;
            }
        });

});

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

Post a Comment for "Capture First Visible Div Id While Scrolling (viewport)"