0

I'm trying to hide a "sticky" div once it scrolls past the next parent div. I've currently successfully have it so it appears after scrolling "y > 100" but I'm having a lot of trouble getting the "Sticky Note" to disappear after scrolling past #break.

Example below.

http://codepen.io/anon/pen/BojKBx

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 100) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }

});
.bottomMenu {

  display: none;

  position: fixed;

  bottom: 0;

  width: 50%;

  height: 60px;

  border-bottom: 1px solid #000;

  z-index: 1;

  margin: 0 auto;

  left: 50%;

  margin-left: -500px;

  text-align: center;

}

#header {

  font-size: 50px;

  text-align: center;

  height: 60px;

  width: 100%;

  background-color: red;

}

#container {

  height: 2500px;

}

#break {

  text-align: center;

  font-size: 30px;

  margin-bottom: 300px;

  width: 100%;

  background-color: yellow;

}

#footer {

  height: 60px;

  background-color: red;

  width: 100%;

  bottom: 0;

}
<div id="header">Home</div>
<div class="bottomMenu">
  <h2>Sticky Note</h2>
</div>
<div id="container"></div>
<div id="break">Should Not Be Seen After This Point</div>
<div id="footer"></div>
Dan G
  • 3
  • 3
  • Why reinvent the wheel? There is a jQuery plugin called ScrollToFixed https://github.com/bigspotteddog/ScrollToFixed which has this feature and is easy to implement. – Steyn Sep 14 '15 at 08:40

1 Answers1

0

You can get Y position of a div (its vertical offset starting from the top of the page), and then add condition to show sticky note only when you're below the required "Y" coordinate, and above the required div. Example: http://codepen.io/anon/pen/EVPKyP

Javascript code:

$(document).scroll(function () {
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = document.getElementById("break").getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top - window.innerHeight;
    var y = $(this).scrollTop();
    if (y > 100 && y < offset) {
        $('.bottomMenu').fadeIn();
    } else {
        $('.bottomMenu').fadeOut();
    }

});

Sources:

Retrieve the position (X,Y) of an HTML element

screen width vs visible portion

Community
  • 1
  • 1
Yuri Predborski
  • 186
  • 1
  • 1
  • 12