JJS
JJS

Reputation: 33

How to remove sticky class once div returns to its original point

I've got two navbars, the second becomes sticky once it hits the top of the viewport, the problem I'm having is getting it to 'unstick' when the div above which contains the original navbar comes back into the viewport so the first navbar can be seen again .

Sorry for the terrible explanation and vague title, had trouble trying to thing of how to describe it.

Here's a jsfiddle which will give you a much better idea of what I mean, any help would be appreciate as I'm pretty poor when it comes to javascript, thanks.

(HTML and CSS in jfiddle)

  $('#nav2').attr("attop", false);
  var lastScrollTop = 0;
  $(window).on('scroll', function() {
    var windowScrollTop = $(this).scrollTop();


    if (windowScrollTop > lastScrollTop) {
      var header = $('#nav2[attop="false"]:first');
      if (header && header.length > 0) {
        if (windowScrollTop >= header.offset().top) {
          header.attr('attop', true);
          $('#nav2').addClass('sticky');
        }
      }

    }

    lastScrollTop = windowScrollTop;

  });
});
````

Upvotes: 3

Views: 691

Answers (1)

Jakub Muda
Jakub Muda

Reputation: 6734

There is a nice solution in Bootstrap 4 and I use it on a few sites. The only thing you need to do is to add this class to the navbar. Check out the snippet below.

Notice that in order for position sticky to work correctly this class can't be added to an element inside a container, you must add this class to the container itself.

@supports ((position: -webkit-sticky) or (position: sticky)) {
  .sticky-top {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
    z-index: 1020;
  }
}

/*DEMO PURPOSE*/
nav{background:red;padding-top:1rem;padding-bottom:1rem}
.section-1{height:300px}
.section-2{height:1000px}
<div class="section-1">Section 1</div>
<nav class="sticky-top">Lorem Ipsum</nav>
<div class="section-2">Section 1</div>

Upvotes: 1

Related Questions