C
C
Cal_Lightman2021-01-27 10:01:33
JavaScript
Cal_Lightman, 2021-01-27 10:01:33

Sticky navigation menu in pure JS, how to make?

How will the pure JS version of the script look like?
There are many options on the Internet, but they do not work in all browsers and also do not work with other scripts nearby ....

Now on JQuery, the code with markup looks like this:

<nav id="menu" class="default">
<div class="menu_list">
 ...
</div>
</nav>


$(function(){
  var menu = $("#menu");
  $(window).scroll(function(){
    if($(this).scrollTop() > 150 && menu.hasClass("default")){
      menu.removeClass("default").addClass("fixed");
    }
    else if($(this).scrollTop() <= 150 && menu.hasClass("fixed")){
      menu.removeClass("fixed").addClass("default");
    }
  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2021-01-27
@Cal_Lightman

document.addEventListener("DOMContentLoaded", onDOMReady);

function onDOMReady() {
  window.addEventListener('scroll', onWindowScroll)

  var menu = document.getElementById('menu');

  function onWindowScroll() {
    if(window.document.scrollingElement.scrollTop > 150){
      menu.classList.add("fixed");
    }
    else { 
      menu.classList.remove("fixed")
    }
  }
}

Document Load Events
Document.scrollingElement

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question