简体   繁体   中英

How to convert this JQuery on scroll to Vanilla JS

Here is the code:

$(document).ready(function() {
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        var navbar = $('#navbar');

        // if win >= navbar and not already a sticky
        if (windowpos >= navbar.position().top && !navbar.hasClass("navbar-fixed-top") ) {
            navbar.addClass("navbar-fixed-top");

        // if win <= navbar and is a sticky
        } else if( windowpos <= navbar.position().top && navbar.hasClass("navbar-fixed-top")  ) {
            navbar.removeClass("navbar-fixed-top");
        }
    });
});

What it does is to keep the navbar background transparent on windows onload; but makes the navbar visible with a different background color when scrolled.

You can use: addEventListener("scroll", callbackFunction)

Like so:

window.addEventListener("scroll", function() {
  const windowpos = document.querySelector("html").scrollTop;
  const navbar = document.querySelector("#navbar");
  const navbarTopPos = navbar.getBoundingClientRect().top;

  if (windowpos >= navbarTopPos && !navbar.classList.contains("navbar-fixed-top")) {
    navbar.classList.add("navbar-fixed-top");
  } 
  else if( windowpos <= navbarTopPos && navbar.classList.contains("navbar-fixed-top")) {
    navbar.classList.remove("navbar-fixed-top");
  }
})


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM