Max Di Campo
Max Di Campo

Reputation: 438

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?

Upvotes: 1

Views: 65

Answers (2)

Umair Abid
Umair Abid

Reputation: 1463

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"

Upvotes: 0

Isitea
Isitea

Reputation: 751

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.

Upvotes: 1

Related Questions