Javascript to have a fixed navbar is not working

http://www.new.techmoney360.com/ is the website and it’s being developed with wordpress.

That navigarion bar is part of the <header> that also encompass my logo section up top so I’m not sure if that causing issues.

Read More

This is the entire html the encompasses the navigation bar that I want to stick to the top when I scroll past it.

<div  id="navmenu" class="mkd-menu-area">
    <div class="mkd-grid">
        <div class="mkd-vertical-align-containers">
            <div class="mkd-position-left">
                <div class="mkd-position-left-inner">
                    <?php if(is_active_sidebar('mkd-left-from-main-menu')) : ?>
                        <?php dynamic_sidebar('mkd-left-from-main-menu'); ?>
                    <?php endif; ?>
                    <?php discussion_get_main_menu(); ?>
                </div>
            </div>
            <div class="mkd-position-right">
                <div class="mkd-position-right-inner">
                    <?php if(is_active_sidebar('mkd-right-from-main-menu')) : ?>
                        <?php dynamic_sidebar('mkd-right-from-main-menu'); ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

This is the javascript I’m using to target the navigation bar (thanks to akinuri for the script)

window.onscroll = changePos;

function changePos() {
   var header = document.getElementById("navmenu");
   if (window.pageYOffset > 182) {
      header.style.position = "absolute";
      header.style.top = pageYOffset + "px";
   } else {
      header.style.position = "";
      header.style.top = "";
   }
}

Related posts

Leave a Reply

2 comments

  1. Place .mkd-top-bar outside of all wrappers and whatnot, place it below the <body> and in it’s css apply position: fixed;

    .mkd-top-bar {
        background-color: #303030;
        position: fixed;
    }
    

    Is this what you’re looking for?

  2. @Jacob is partially correct, you don’t need (as much) JavaScript here. Here’s how you can resolve the issue. Replace the current functionality with this:

    window.onscroll = stickyNav;
    
    function stickyNav() {
       var header = document.getElementById("navmenu");
       if (window.pageYOffset > 70) {
          header.classList.add("sticky");
       } else {
          header.classList.remove("sticky");
       }
    }
    

    Then, create a new class called .sticky with the following styling adjustments:

    .sticky {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
    }
    

    Edit: update stickNav to stickyNav.