jQuery: Showing/Hiding HTML Elements Based on Scroll Position

Showing/hiding any HTML DOM element is a common scenario based on various business requirements. Since the time of SPA (single page application) is evolved, you will find that on scroll position of browser, new elements are shown and previous elements are hidden. There are tons of jQuery plugins available which can show/hide any HTML element based on the scroll position but it’s not advisable to use jQuery plugins for things which you can do with simple jQuery code. So in this post, let’s see how to show/hide any HTML element based on the scroll position in the browser window using jQuery.

First, we need to get the scroll position. Out of the box jQuery provides a function scrollTop() which gets the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

HTML

For the demo, there are some empty div elements at the top and bottom so that scroll bar appears in the browser. And there are 2 div elements dvContent and dvContent2 which will be shown/hidden based on the scrollbar position.

<div style="height:100px;">
</div>
<div id="dvContent" style="height:100px;">
  your HTML content
  <br />your HTML content
  <br />your HTML content
  <br />your HTML content
  <br />
</div>

<div id="dvContent2" style="height:100px;">
  your HTML content 1
  <br /> your HTML content 2
  <br /> your HTML content 3
  <br /> your HTML content 4
  <br />
</div>
<div style="height:800px;">
</div>

jQuery

Here is the jQuery code, which first hides the dvContent2 and then binds the scroll event to window object. Within the scroll event, first check for scrollTop() function returned value. If it’s greater than or equal to 100, then hide the dvContent and show the dvContent2 div. And in the other part, do the opposite.

$(function() {
  $('#dvContent2').hide();
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= 100) {
      $('#dvContent').hide();
      $('#dvContent2').show();
    } else {
      $('#dvContent').show();
      $('#dvContent2').hide();
    }
  });
})

As you can see, it’s pretty easy to show/hide any DOM element based of the browsers scroll bar position.



Responsive Menu
Add more content here...