Skip to content
Advertisement

Show div when on scroll and class called

I have a one page app that has 2 sidenavs (nav1 and nav2) and 2 different contents of div. Now I want to do is when I scroll down and get to the point where class="content2" is there, id="nav2" will show. Then if I scroll up where class="content1" is there then the id="nav1" will show. As default nav1 shall be shown.

here’s some pictures to understand the problem a little

Here’s a picture where I am in the content1. enter image description here

And here in content2 enter image description here

and here’s a sample html fiddle.

Advertisement

Answer

You can use $(document).scroll(function() to detect a change in scroll position of the document. scrollTop() method will give the current top position of the document and position() is the method which returns an object containing position values and top is what we want in our case. We just want to compare current document top position and div top position.

if($(this).scrollTop()>=$('.content2').position().top){ which means the current document position is with in the top position of the div with class name .content2. now we can show nav2 and hide nav1. Otherwise show nav1 and hide nav2

  $(document).scroll(function() {
    if($(this).scrollTop()>=$('.content2').position().top){
      $("#nav2").show();
      $("#nav1").hide();
    }
    else {
      $("#nav1").show();
      $("#nav2").hide();
    }
  })

Fiddle: https://fiddle.jshell.net/tintucraju/rjjrmhvt/5/

Please note : position().top is calculated from the top to the parent if parent is relatively positioned. so there will be slight change in the top value. you can adjust by adding offset to $(this).scrollTop() and adjust to your desired position.

Updated Fiddle : https://fiddle.jshell.net/tintucraju/rjjrmhvt/6/

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement