Ad
Change Menuitem Based On Scroll Position Using Javascript
Changing the menu item in navigation bar based on scroll position using javascript.
i have changed the menu item on click. but don't know how to change the active menu item based on scroll position. I have tried getting the pageYoffset
. it is a very long process and too looks like repetition. is this the right way to do it or is there an efficient way to do so.
HTML CODE:
<nav class="navbar navbar-expand-lg navbar-light">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li id="home" class="nav-item active">
<a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#homeSection"><i class="fa fa-home"></i></a>
</li>
<li id="about" class="nav-item">
<a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#aboutSection"><i class="fa fa-user"></i></a>
</li>
<li id="skill" class="nav-item">
<a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#skillSection"><i class="fa fa-cogs"></i></a>
</li>
<li id="work" class="nav-item">
<a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#workSection"><i class="fa fa-eye"></i></a>
</li>
<li id="contact" class="nav-item">
<a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#contactSection"><i class="fa fa-envelope"></i></a>
</li>
</ul>
</div>
</nav>
JAVASCRIPT:
let header = document.getElementById("navbarNav");
let btns = header.getElementsByClassName("nav-item");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
let current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
Ad
Answer
The code can be minimised using jquery. BUt if you want to use javascript alone, you will have a little longer code. Get the scolltop value of each section during scroll event and assign the active class
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad