thrashead thrashead - 5 months ago 13
HTML Question

How to detect window top is equal to any section top on window scrolling

I have many sections in my webpage. I want to add them a class name "active" while i am scrolling in the page if window.top is equal to any section.top. I mean i want to know that i am on the section or not. Can i do that? All sections have their own data-id attribute. I tried something like below but it didn't make any sense;

$(window).scroll(function () {
if ($(this).top == $("section").offset().top) {
$("section").addClass("active");
}
});

Answer

Try this function:

$.fn.isOnScreen = function(){

var win = $(window);

var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Use it:

$(window).scroll(function () {
    if ($(this).isOnScreen()) {
        $("section").addClass("active");
    }
});

Good luck!

Reference: http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen