Skip to content
Advertisement

Add class to element when scrolled into view (scrollable div)

Is there a solution for adding a class to the element in view when scrolling, and removing when out of view? This needs to work for a scrollable div. I have found a few solutions so far but they only seem to work for body… not a scrollable div.

I am happy to use a plugin if you know one exists. Something like this…

if ($('.journal-slider .each-slide img').inViewport() ) {
    $(this).addClass('in-view');
} else {
   $('.journal-slider .each-slide img').removeClass('in-view');
}

Thanks, R

Advertisement

Answer

The plugin you are looking for is called waypoints

Quote from the “Get Started” :

“Let’s say you have a div with overflow:scroll, and you want a waypoint inside of this scrollable element. The context option lets you do this. Scroll the box below.”

$('#example-context').waypoint(function() {
    notify('Hit top of context');
}, { context: '.example-scroll-div' });

EDIT: Not using waypoints

Based on what you already did, I came to this :

function  checkInView(elem,partial)
{
    var container = $(".scrollable");
    var contHeight = container.height();
    var contTop = container.scrollTop();
    var contBottom = contTop + contHeight ;
 
    var elemTop = $(elem).offset().top - container.offset().top;
    var elemBottom = elemTop + $(elem).height();

    var isTotal = (elemTop >= 0 && elemBottom <=contHeight);
    var isPart = ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= container.height())) && partial ;

    return  isTotal  || isPart ;
}

$(document).ready(function(){
$(".scrollable").scroll(function(){
    var result="",result2="";
   $.each( $(".scrollable p"),function(i,e){
       if (checkInView($(e),false)) {
           $( this ).addClass( "red" );
       } else {
           $( this ).removeClass( "red" );
       }
        result += " " +  checkInView($(e),false);
       result2 += " " +  checkInView($(e),true);
    });
    $("#tt").text(result);
    $("#kk").text(result2);
});
});
.scrollable{
    margin:10px;
    height:100px;
    overflow-y:scroll;
}
p
{
    border-width:1px;
    border-color:black;
    border-style:solid;
}
.red {
    background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
full:  <div id="tt"></div>
part: <div id="kk"></div>
<div class="scrollable">
    <p>item1<span></span></p>
    <p>item2<span></span></p>
    <p>item3<span></span></p>
    <p>item4<span></span></p>
    <p>item5<span></span></p>
    <p>item6<span></span></p>
    <p>item7<span></span></p>
    <p>item8<span></span></p>
</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement