Show/Hide an element on scroll

onscroll

This tutorial shows you how to show an element once you have scrolled the page till a point and then hide it when scrolled back.

Lets consider we need to show a footer div once you have scrolled till 1000px.

First we will create the div which is to be shown as a footer.


<div id="footer">
    Footer Text
</div>

And then the CSS with the display property set to ‘none’.


#footer {
  position: fixed;
  bottom: 0;
  width:100%;
  color: #FFF;
  background-color: rgba(0, 0, 0);
  font-size: 12px;
  padding: 1em;
  display: none;
}

Now include the jQuery file in the head section


<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>

and then the code that does the trick.


jQuery(document).ready(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 1000) {
      jQuery('#footer').fadeIn(500);
    } else {
      jQuery('#footer').fadeOut(500);
    }
  });
});

Leave a Reply

Your email address will not be published.