1

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?

Max Di Campo
  • 319
  • 1
  • 2
  • 10
  • Have you checked the console are resources loading correctly ? – Zvezdas1989 Apr 24 '18 at 08:03
  • Try out [this answer](https://stackoverflow.com/a/33979503/2363481) and [this CodePen](https://codepen.io/BoyWithSilverWings/pen/MJgQqR). – Daan Apr 24 '18 at 08:54

2 Answers2

1

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.

Isitea
  • 691
  • 5
  • 12
0

In case you are interested in non jquery way

var one = document.getElementById("one")
var sticky = document.getElementById("sticky")

window.addEventListener("scroll", function() {
  var c1 = one.offsetTop > window.pageYOffset
  var c2 = (one.offsetTop + one.offsetHeight) > (window.pageYOffset)

  if (c1 || c2) {
    sticky.style.display = "block"
  } else {
    sticky.style.display = "none"
  }
})

You can see it working here https://jsbin.com/garokag/edit?js,output

This solution doesn't depend on css props to get height of element, it picks it directly form DOM. However displaying sticky whenever "one" is in view port doesn't necessarily mean it will always appear at bottom on "one"

Umair Abid
  • 1,403
  • 2
  • 18
  • 34