javascripthtmljqueryaffix

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


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");
        }
    });         
});

Solution

  • 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');
      }
    });