1
<div id="title-box">
    <div class="title">Title</div>
</div>

<div id="gallery">
    <div class="gallery-image"></div>
    <div class="gallery-image"></div> 
    <div class="gallery-image"></div>
    <div class="gallery-image"></div> 
</div>

<div id="text-box">
    <div class="text">
        One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin...
    </div>
</div>

I tried various jQuery plugins, but I could not get the desired result. I would like to add a class to the body when the "gallery" element is visible in the viewport, and to remove a class in the body when the "gallery" item is no longer visible.

I'm new to jQuery.

2 Answers2

1

Please try this

$(document).ready(function(){
    $('#gallery').bind('inview', function (event, visible) {

        if (visible == true) {
        // element is now visible in the viewport
            $('body').addClass('myclass');
        }
        else{
           $('body').removeClass('myclass');
           alert('removed... pleasecheck body');
        }  
    });
    $('#gallery').trigger('inview');
});

DEMO

Rino Raj
  • 6,041
  • 2
  • 22
  • 37
0

You can check whether the element is out of view port or not. Depending upon the return you can add the class

function isElementOutOfViewport (el) {
    var rect = el.getBoundingClientRect();
    return rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight;
}

alert(isElementOutOfViewport(document.getElementById('bottom')));
.bottom {margin-top:100vH}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="title-box">
    <div class="title">Title</div>
</div>

<div id="gallery">
    <div class="gallery-image"></div>
    <div class="gallery-image"></div> 
    <div class="gallery-image"></div>
    <div class="gallery-image"></div> 
</div>

<div id="text-box">
    <div class="text">
        One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin...
    </div>
</div>
<div id="bottom" class="bottom">Not in view port</div>
Tushar
  • 11,306
  • 1
  • 21
  • 41