How to convert this jQuery code to plain Javascript (HTML Affix)?

47 Views Asked by At

Can someone please help me convert this jQuery code to plain JS? This is when you scroll down a page, the navigation menu will be fixed.

$(document).ready(function() {
    var mainMenu = $('.primaryNav').offset();
    $window = $(window);
     $window.scroll(function() {
        if ($window.scrollTop() >= mainMenu.top) {
            $(".primaryNav").addClass("affix");
        }
        else {
            $(".primaryNav").removeClass("affix");
        }
    });         
});
1

There are 1 best solutions below

0
Kyle Wetton On BEST ANSWER

Here we go

const nav = document.querySelector('.primaryNav');
const mainMenuTop = nav.getBoundingClientRect().top;

window.addEventListener('scroll', function(e) {
   if (window.pageYOffset >= mainMenuTop) {
    nav.classList.add('affix');
   } else {
    nav.classList.remove('affix');
  }
});