Robolisk Robolisk - 6 months ago 24
CSS Question

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.

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

Answer

@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.

Comments