How to determine the scroll position of the "article" and add a class

I have four different articles with different content. All I need to do is when the scroll position reaches the top position of the article to be added with the active class. I have not been successful. Here is the code I've tried so far.

Html

<article></article>
<article></article>
<article></article>
<article></article>

      

CSS

article{
    height: 800px;
    background-color: gray;
}
article:nth-child(2){
    background-color: blue;
}
article:nth-child(3){
    background-color: pink;
}
article:last-child{
    background-color: orange;
}
article.active{
    background-color: red;
}

      

JQuery

var scrollPosition = $('article').scrollTop();
$(window).scroll(function () {
    if ($(window).scrollTop() == scrollPosition) {
        $(this).addClass('active');
    } else {
        $(this).removeClass('active');
    }
})

      

Working demo

+3


source to share


1 answer


I recommend using . offset () to get the absolute position of the element.

Here's an example:

$(window).scroll(function () {
    $('article').each(function () {
        var ArtOffsetTop = $(this).offset().top;
        var ArtOffsetBottom = $(this).offset().top + $(this).height();
        if (($(window).scrollTop() >= ArtOffsetTop) && ($(window).scrollTop() <= ArtOffsetBottom)) {
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    })
})

      



Live demo


I am adding a new variable ArtOffsetBottom

to determine if it is $(window).scrollTop()

between the top and bottom of the article.

+3


source







All Articles