Add active class to nav menu on click of link - javascript

I am developing a web page wherein I have header(containing the navigational menu) in separate html file say reusableheader.html and footer in separate file i.e. reusablefooter.html.
reusableheader.html:
<style>
.nav-menu a:hover, .nav-menu .active > a, .nav-menu li:hover > a {
color: #3fbbc0;
border-color: #3fbbc0;
}
</style>
<script>
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function()
{
if ($(this).attr("href") !== "#")
{
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL)
{
$("a").parent("li").removeClass("active");
$(this).parent("li").addClass("active");
return false;
}
}
});
});
</script>
<nav class="nav-menu d-none d-lg-block"> //set to fixed-top.
<ul>
<li class="active"><a class="nav-link" href="/hospital/">Home</a></li>
<li><a class="nav-link" href="/hospital/aboutus">About</a></li>
<li><a class="nav-link" href="/hospital/services">Services</a></li>
<li><a class="nav-link" href="/hospital/departments">Departments</a></li>
<li><a class="nav-link" href="/hospital/doctors">Doctors</a></li>
<li class="drop-down"><a class="nav-link" href="#">Reach Us</a>
<ul>
<li><a class="nav-link" href="/hospital/contact">Contact Us</a></li>
<li><a class="nav-link" href="#">Feedback</a></li>
<li><a class="nav-link" href="#">Blogs</a></li>
<li><a class="nav-link" href="#">Newsletters</a></li>
</ul>
</li>
</ul>
</nav><!-- .nav-menu -->
I am including the below javascript code in all my other web pages:
otherpages.jsp
<script>
$(function() {
$("#header").load("reusableheader.html");
});
</script>
The above code works fine i.e. on click of link on the menu item, its becomes the active link with the color assigned(in css) but when I scroll the page down, the activeness shifts from currently active link back to the "home" link.
What am I doing wrong here?

I think the problem is with removing the active class on the li element. How can you say $("a").parent("li").removeClass("active"); when you have got so many a elements with parent li element.
Instead, create a new for loop function which removes the element if the active class is found regardless of wherever it is in the list. And also add the logic on the click event of the li element, otherwise, it keeps looking for a URL match and changes it and would behave oddly if any path gets appended to the URL.
function removeClass() {
var listItems = $(".nav-menu > ul > li");
listItems.each(function (idx, li) {
$(li).removeClass("active");
});
}

Related

Adding an active class to the navbar

This is how my code looks like:
<div class="header-nav navbar-collapse collapse ">
<ul id="navigation" class=" nav navbar-nav">
<li>
Home
</li>
<li>
About Us
</li>
</ul>
</div>
I've been trying to add the active class to each of them when the user is on that specific page but no succes so far
Tis is how my script looks like:
var i = 0;
[].forEach.call(document.querySelectorAll('li > a'), function(nav) {
console.log(nav.pathname,window.location.pathname);
if (nav.pathname === window.location.pathname){
i = 1;
console.log(i);
nav.classList.add('active')
}
else{
console.log(i)
nav.classList.removeClass('active')
}
})
The active class is set on the "a" not on "li" and i don't know how to fix this. Maybe someone can help me?
In looking at the classes, it looks like you may be using Bootstrap. I added in those libs to the snippet, and updated some of the classes. I also added in another nav item with the href equal to js since that is the pathname for the snippet window. Otherwise it won't add the active class as there would not be a pathname that would be equal.
I also changed the nav items to pills, so you can see the active link easier.
var i = 0;
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.classList.add('active')
} else {
nav.classList.remove('active')
}
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div class="navbar navbar-light bg-light">
<ul id="navigation" class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="js">JS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about-us.html">About Us</a>
</li>
</ul>
</div>
To target the parent element, you have a few options - my favorite is element.closest(selector) which takes a starting element and finds the closest containing parent that matches selector
let els = document.querySelectorAll('li > a');
els.forEach(el => {
el.addEventListener('click', e => {
els.forEach(a => a.closest('li').classList.remove('active'));
e.target.closest('li').classList.add('active');
})
})
li.active {
background-color: green;
}
<ul>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
</ul>
Thanks for this, i merged the two responses and made it into one that works for me, this is the script that worked without even touching the classes into the nav-bar:
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.closest('li').classList.add('active')
} else {
nav.closest('li').classList.remove('active')
}
})

Active link name is not changing color in bootstrap navbar

This is a single-page website currently I am working on. But When I click another link in the navbar it's not changing color though hovering is working perfectly. Here is my html code :
<html>
<body>
<div class="collapse navbar-collapse justify-content-between" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 ">
<li class="nav-item ">
<a class="nav-link scroll active " aria-current="page" href="#intro">Home</a>
</li>
<li class="nav-item">
<a class="nav-link scroll" href="#about">About Us </a>
</li>
<li class="nav-item">
<a class="nav-link scroll" href="#services">Services</a>
</li>
<li class="nav-item">
<a class="nav-link scroll" href="#">Products</a>
</li>
</ul>
</div>
</html>
</body>
enter image description here
Here is my css:
<style>
.navbar .nav-item a {
color: #5cbf8f !important;
}
.navbar .nav-item a:hover {
color: #028b77 !important;
}
.navbar .nav-item a.active {
color: #028b77 !important;
}
</style>
enter image description here
Here is my Js :
<script>
$(document).ready(function () {
var scrollLink = $(".scroll");
// Smooth scrolling
scrollLink.click(function (e) {
e.preventDefault();
$("body,html").animate(
{
scrollTop: $(this.hash).offset().top,
},
1000
);
});
// Active link switching
$(window).scroll(function () {
var scrollbarLocation = $(this).scrollTop();
scrollLink.each(function () {
var sectionOffset = $(this.hash).offset().top - 20;
if (sectionOffset <= scrollbarLocation) {
$(this).parent().addClass("active");
$(this).parent().siblings().removeClass("active");
}
});
});
});
</script>
enter image description here
N.B: Don't really know about js, just found it on the internet.
Navbar:
enter image description here
I think your js is wrong.
$('.active').removeClass('active');
$(this).addClass('active');
More efficient options are available if the DOM hierarchy is known.
For example, if they're all siblings, you can use this:
$(this).addClass('active').siblings('.active').removeClass('active');

Navbar active page

I have this one problem regarding the highlighted navbar menu which will only highlight when we clicked on it. For that to work, I'm using javascript. However, each pages has its own sub pages, for example, page Home has a link of local/home, but its content will lead to local/home/content. The sub link will not make the navbar to function The navbar was coded in different file, which I just extends in the home and other pages. I'm not very good at explaining but if I can elaborate more on any part I would do so. Below I attached my JS and my navbar:
Navbar :
<ul class="navbar-nav mr-auto" id="nav">
<li class="nav-item">
<a class="nav-link active" href="{{ url('/') }}">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('courses') }}">opportunities</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('events') }}">events</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('uqalc') }}">courses</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('contact') }}">contact</a>
</li>
</ul>
Javascript :
const currloc = location.href;
const menuItem = document.querySelectorAll('a');
const menuLen = menuItem.length;
for (let i = 0; i < menuLen; i++) {
menuItem[i].classList.remove('active');
if (menuItem[i].href === currloc) {
menuItem[i].className = "nav-link active";
}
}
Here, I add active class to the anchor tag which is inside .navbar-nav If the window location is https://www.google.com/index.html
then this code find an anchor tag which one inside the .navbar-nav if anchor tag href should be index.html then this code add class active to the anchor tag
function removeQueryString(url) {
return url.split('?')[0]
}
[].forEach.call(document.querySelectorAll('.navbar-nav a'), function(elem) {
if (removeQueryString(elem.href) === removeQueryString(window.location.href))
elem.classList.add('active')
else
elem.classList.remove('active')
})

trigger click on next tab in jQuery

How to trigger click on next tab in jQuery, I have tried below code but not working, TIA.
var c = $('ul#tabs li').length;
var selected = parseInt($('ul#tabs li.active').index())+1;
if (c != selected) {
$("ul#tabs li:nth-child(" + selected + ")").click();
return false;
}
<div id="mytabs">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a data-toggle="tab" href="#Personal" aria-expanded="false">Personal</a></li>
<li><a data-toggle="tab" href="#Business">Business</a></li>
<li><a data-toggle="tab" href="#Documents" aria-expanded="true">Documents</a></li>
<li><a data-toggle="tab" href="#References">References</a></li>
<li><a data-toggle="tab" href="#OrderDelivery">Order & Delivery</a></li>
</ul>
</div>
I'm a bit unclear as to what's not working, but the simplified code below is all that's required to get current tab and next tab:
$(document).ready(function() {
let currentTab = $('ul#tabs li.active');
let nextTab = currentTab.next();
// Once you have the tab, click it (clicking after 2 seconds to demonstrate)
setTimeout(function() { nextTab.find("a").get(0).click()}, 2000);
// If you need to do things when a tab is clicked, create an event handler
$('a[data-toggle="tab"]').click(function(event) {
// Do something when a tab is clicked
// For example: Remove active class, and add it to active element
$('a[data-toggle="tab"]').parent().removeClass("active");
// Add active class to clicked li
$(this).parent().addClass("active");
});
});
.active a {
color: green !important;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytabs">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a data-toggle="tab" href="#Personal" aria-expanded="false">Personal</a></li>
<li><a data-toggle="tab" href="#Business">Business</a></li>
<li><a data-toggle="tab" href="#Documents" aria-expanded="true">Documents</a></li>
<li><a data-toggle="tab" href="#References">References</a></li>
<li><a data-toggle="tab" href="#OrderDelivery">Order & Delivery</a></li>
</ul>
</div>

jQuery set class active with anchor

I have a menu like :
<ul>
<li>
<a class="scroll-to" href="#one">one</a>
</li>
<li>
<a class="scroll-to" href="#two">two</a>
</li>
<li>
<a class="scroll-to" href="#three">three</a>
</li>
</ul>
And on my page, multiple anchor like :
<a id="two" target="_blank"></a>
or
<a id="one" target="_blank"></a>
I'm looking for a way to set an active class to my menu when i scroll to an anchor (with click or mouse scroll).
For example if i scroll to my anchor id="two" i need to set active my li #two.
Any ideas ?
If I understand your problem, add your anchors some class, for example section and try this:
$('.section').hover(function() {
var anchor = $(this).attr('id');
$('a[href="#'+anchor+'"]').addClass('active');
}, function() {
$('a').removeClass('active');
});
http://codepen.io/tomekbuszewski/pen/MwMWoK
var links = document.querySelectorAll("a.scroll-to");
console.log(links[1]);
for (var i = links.length -1; i>=0; i--)
{
//click event
links[i].onclick= someHandlerFunction;
//hover event
links[i].onmouseover= someHandlerFunction;
}
var liActive = undefined;
function someHandlerFunction(event) {
if (liActive != undefined) liActive.setAttribute("class", "");
liActive = event.target.parentNode;
liActive.setAttribute("class", "active");
return false;
}
.menu{
background-color: #00ff00;
}
.menu li.active{
background-color: blue;
}
<ul class="menu">
<li>
<a class="scroll-to" href="#one">one</a>
</li>
<li>
<a class="scroll-to" href="#two">two</a>
</li>
<li>
<a class="scroll-to" href="#three">three</a>
</li>
</ul>
Voila (add and remove class in the same time), it's a but it's a bit redundant to add active class at click and hover.

Categories