Search code examples
javascriptjqueryviewport

show/hide div depending if specific class in viewpwort


I try to create a fixed positioned area, which should hide, when a specific area is in the viewport. When the div is outside of the viewport, the fixed area should be shown again.

I use jquery.viewport for it.

My HTML:

<section id="section-1">
  <div class="sticky-info">Sticky</div>
</section>
<section id="section-2">
</section>

My JS:

  $(window).scroll(function () {
      if ($('#section-2').is(':in-viewport')) {
            $( ".sticky-info" ).fadeOut( 100, function() { });
      } else {
            $( ".sticky-info" ).fadeIn( 100, function() { });
      }
  });

Here is the fiddle: https://jsfiddle.net/cnx4pvxu/

In my fiddle, it works perfect. But if I try in my own dummy page, it fades out, but do not fade in again (like in the fiddle). But it's complete the same like in the fiddle...

Here is the dummy page: http://tanzstudio-ludwig.de/test.html

What am I doing wrong? Or is there a better solution?


Solution

  • You must define height and width of body.

    It seems that $().is( ':in-viewport' ) works based on height and width of body.

    Simply, add body { height: 100%; width: 100%; } to your CSS.

    Or not use document.elementFromPoint() instead of jQuery function.