I can't seem to figure out how to make my site navigation have an active link for the current page.
This is the only code that is working for me, however, there is always two links with the class "active." I only want the current page to be active.
Here is my code:
<script>
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
</script>
Here is my staging site: http://champhero.wpengine.com
Thanks for any help!
You are checking an indexOf. Therefore, URL http://champhero.wpengine.com/ is always contained in others like http://champhero.wpengine.com/the-enemies/
If you just check an equality, it should work:
function setActive() {
var aObj = document.getElementById('nav').getElementsByTagName('a');
for (var i = 0; i < aObj.length; i++) {
if (document.location.href == aObj[i].href) {
aObj[i].className = 'active';
}
}
}
Note: You were not declaring local variables with 'var', making them globals and potentially unstable across the environment. i changed that in my suggested code.
a tag href contains whole link so you could check for equality like below.
<script>
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href === aObj[i].href) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
</script>
Home page nav link(http://champhero.wpengine.com/) is highlighted in every page because it's present in all other links(http://champhero.wpengine.com/pagelink)
<script>
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i = 0; i < anchors.length; ++i)
if (anchors[i].href === window.location.href)
anchors[i].className += ' active';
};
</script>
though this snippet will apply the class to all anchors. For just the ones in, say, your navigation bar, give them a specific CSS class to hook into and then:
<script>
window.onload = function(){
var nav_links = document.querySelectorAll('.nav-link');
for (var i = 0; i < nav_links.length; ++i)
if (nav_links[i].href === window.location.href)
nav_links[i].className += ' active';
};
</script>
So I have a list of elements in an array. I'd like to add a jQuery toggle event to each element and pass in two functions as parameters. This is what I have so far, though it's giving me errors, saying that e (the Event Object) is undefined inside moveToSelected and moveToUnselected.
// Getting my array
var selected = document.getElementsByClassName("selected_style");
// The two functions to toggle between:
function moveToSelected(e) {
style = e.target;
style.className = "selected_style";
$('#selected-style').append(e.target);
}
function moveToUnselected(e) {
style = e.target
style.className = "unselected_style";
$('#unselected-style').append(e.target);
}
// Going through the array and adding a toggle event to each element.
for(var i = 0; i < selected.length; i++) {
var element = $(unselected[i]);
element.toggle(moveToSelected, moveToUnselected);
}
HTML, as requested:
<ul id="selected-style">
<li>
Some Style
</li>
<li class="selected_style">
Style
</li>
<li class="selected_style">
Style
</li>
<li class="selected_style">
Style
</li>
</ul>
Thanks for the help!
Uhm, why aren't you using jQuery, this is already built in ?
$('.selected_style').on('click', function() {
$(this).toggleClass('selected_style unselected_style');
if ( $(this).hasClass('selected_style') ) {
$('#selected-style').append(this);
} else {
$('#unselected-style').append(this);
}
});
FIDDLE
The vanilla javascript solution for future viewers. No jQuery required. This is effectively the same script as the accepted answer, without all the overhead of jQuery.
(Demo)
(function () {
"use strict";
var selected = document.getElementById('selected-style');
var unselected = document.getElementById('unselected-style');
var items = document.querySelectorAll('.selected_style'), item;
for (var i = 0; item = items[i]; i++) {
item.onclick = function(){
if(this.className.indexOf('unselected_style') >= 0) {
this.className = this.className.replace(' unselected_style','');
this.className += ' selected_style';
selected.appendChild(this);
} else {
this.className = this.className.replace(' selected_style','');
this.className += ' unselected_style';
unselected.appendChild(this);
}
};
}
})();
I'm trying to add an active class (i.e. class="active") to the appropriate menu list item based upon the page it is on once the page loads. Below is my menu as it stands right now. I've tried every snippet of code I could find in this regard and nothing works. So, can someone please explain simply where and how to add in javascript to define this task?
<ul id="nav">
<li id="navhome">Home</li>
<li id="navmanage">Manage</li>
<li id="navdocso">Documents</li>
<li id="navadmin">Admin Panel</li>
<li id="navpast">View Past</li>
</ul>
Here is an example of the javascript that I'm putting in my head tag in my site master. What am I doing wrong?
$(document).ready(function () {
$(function () {
$('li a').click(function (e) {
e.preventDefault();
$('a').removeClass('active');
$(this).addClass('active');
});
});
});
The reason this isn't working is because the javascript is executing, then the page is reloading which nullifies the 'active' class. What you probably want to do is something like:
$(function(){
var current = location.pathname;
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
.active, a.active {
color: red;
}
a {
color: #337ab7;
text-decoration: none;
}
li{
list-style:none;
}
<h3>Add Active Navigation Class to Menu Item</h3>
<ul>
<li>Home</li>
<li>About</li>
</ul>
<h2>Live Demo</h2>
With VANILLA plain JavaScript
(function () {
var current = location.pathname.split('/')[1];
if (current === "") return;
var menuItems = document.querySelectorAll('.menu-item a');
for (var i = 0, len = menuItems.length; i < len; i++) {
if (menuItems[i].getAttribute("href").indexOf(current) !== -1) {
menuItems[i].className += "is-active";
}
}
})();
ES6 version, that works properly in cases when your link is to "/products" and you have subroutes, like: "/products/new", "/products/edit", etc.
let switchNavMenuItem = (menuItems) => {
var current = location.pathname
$.each(menuItems, (index, item) => {
$(item).removeClass('active')
if ((current.includes($(item).attr('href')) && $(item).attr('href') !== "/") || ($(item).attr('href') === "/" && current === "/")){
$(item).addClass('active')
}
})
}
$(document).ready(() => {
switchNavMenuItem($('#nav li a, #nav li link'))
})
If your menu need add the active class in li, you need use this code above.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).closest('li').addClass('active');
}
});
});
$(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
$( ".top-menu li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd)
$(this).addClass('active')
});
});
This on page JS code is a 100% working put your id and enjoy it.
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
console.log(CurrentUrlEnd);
$( "#lu-ID li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd){
$(this).closest('li').addClass('active')
}
});
});
None of the above solutions worked for me. Finally this javascript solution worked.
<script>
function setActive() {
linkObj = document.getElementById('premier-topnav').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
if(document.location.href.indexOf(linkObj[i].href)>=0) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
</script>
premier-topnav is the id of navbar div.
.active class is defined as:
#premier-topnav .active {
color: brown;
}
var cururl = window.location.pathname;
var curpage = cururl.substr(cururl.lastIndexOf('/') + 1);
var hash = window.location.hash.substr(1);
if((curpage == "" || curpage == "/" || curpage == "admin") && hash=="")
{
//$("nav .navbar-nav > li:first-child").addClass("active");
}
else
{
$(".topmenu li").each(function()
{
$(this).removeClass("active");
});
if(hash != "")
$(".topmenu li a[href*='"+hash+"']").parents("li").addClass("active");
else
$(".topmenu li a[href*='"+curpage+"']").parents("li").addClass("active");
}
Rob.M got it right.
I'm just going to post my solution since his didn't really work for me. i have a small change in comparison to him. assuming you have different paths to each link.
(function() {
var current = location.pathname;
$('#navbar ul li a').each(function() {
var $this = $(this);
// we check comparison between current page and attribute redirection.
if ($this.attr('href') === current) {
$this.addClass('active');
}
});
})();
This worked perfectly for me.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).addClass('active');
}
});
});
I know it been quite a while this question was asked. Here is the answer which will work without jQuery:
var activeNavlink = document.querySelectorAll('nav a[href^="/' + location.pathname.split("/")[1] + '"]');
activeNavlink[0].classList.add('active');
Hope this helps.
If you want for master page in asp .net just put this code inside body tag
<script type="text/javascript">
jQuery(function ($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function () {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
Thank you
This should do your job in one liner.
document.querySelector(`a[href^='${location.pathname.split('/'[1])}']`).className = 'active'
jQuery style:
$('a[href="'+ window.location.href + '"]').css({
backgroundColor: 'red',
color: 'white'
})
In first line use this if you have relative links
$('a[href="'+ window.location.path + '"]').css({
Or both
$('a[href="'+ window.location.href + '"], a[href="'+ window.location.path + '"]').css({
$(function(){
//this returns the whole url
var current = window.location.href;
//this identifies the list you are targeting
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is exactly like this link, make it active
if($this.attr('href') === current){
//this takes care of ul inside a ul, it opens and make active the selected li
$this.parents('.dropdown-menu').toggle();
$this.css('color', 'red');
}
})
});
The bellow jquery script will match the manu if the page has any query string parameter as well. This script is helpful for links with nearly same name.
<script>
//select current menu Item
$(function () {
var current = location.pathname.toLocaleLowerCase();
$('.sidebar li a').each(function () {
var $this = $(this);
var href = $this.attr('href');
href = href.replace(/\?.*/, "").toLocaleLowerCase();
// if the current path is equal to this link, make it active
if (href === current) {
$this.addClass('active');
}
})
})
</script>
Accessible Version:
Here's an accessible version inspired by rob.
I didn't want to run this script on the homepage so I check if it's the homepage
I check if the link matches the exact page instead of checking if it's included in the path. Or else you would get multiple items in the query.
JS
function activateCurrentPage(menuItems){
var current = location.pathname;
if (current !== "/") {
menuItems.each(function(){
var $this = $(this);
if($this.attr('href') === current){
$this.addClass('active');
$this.attr('aria-current', 'page');
}
});
};
}
activateCurrentPage( $('#nav li a') );
CSS
Then for CSS don't target the active class instead target the aria attribute.
#nav a[aria-current="page"]{
color:red;
}
Saw somethng wth plain Javascript
https://www.youtube.com/watch?v=BI3kNsTruWo&ab_channel=OnlineTutorials
Put it in <script> tags after header in my Wordpress site
(function () {
const currentLocation = location.href;
console.log(currentLocation);
const menuItem = document.getElementsByClassName('nav-item');
const menuLength = menuItem.length
for ( i = 0; i < menuLength; i++){
if(menuItem[i].href === currentLocation){
menuItem[i].className += " active"
}
}
})();
<a class="nav-item" href="/ideja/">Ideja</a>
<a class="nav-item" href="/piesaki-sapni/">Piesaki Sapni</a>
<a class="nav-item" href="/uznemejiem/">Uzņēmējiem</a>
<a class="nav-item" href="/sapnu-banka/">Sapņu banka</a>
<a class="nav-item" href="/sapnus-atbalsta/">Sapņus atbalsta</a>
<a class="nav-item" href="/99-iedvesmas-stasti/">99 iedvesmas stāsti</a>
<a id="lv" class="active" href="#">LV</a>
<a href="javascript:void(0);" class="icon" onclick="openNavbar()">
<div id="hamburger" class="hamburger "></div>
</a>
i was having troubles where the link to the root would light up if any page was selected when using Networker's example. this will prevent that for the root pae:
function setActive() {
linkObj = document.getElementById('menu').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
const url = new URL(window.location.href);
if((document.location.href.indexOf(linkObj[i].href)>=0 && linkObj[i].href != url.protocol+"//"+url.hostname+"/") || document.location.href == linkObj[i].href) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
This Does the Job Done For me...
Put this before the ending of body tag
$(function () {
var current = location.pathname;
console.log(current);
if (current == "/") {
$('#home').addClass('active'); //#home is the id for root link.
}
else {
$('#navbarCollapse div a').each(function () {
var $this = $(this);
// if the current path is like this link, make it active
if ($this.attr('href').indexOf(current) !== -1) {
$this.addClass('active');
}
})
}
})
Classes can make the life a whole way easier.
css
<nav>
<ul class="nav-list">
<li class="nav-list-item"><a class="nav-link nav-link-active" href="index.html">Home</a></li>
<li class="nav-list-item"><a class="nav-link" href="about.html">About Me</a></li>
<li class="nav-list-item"><a class="nav-link" href="posts.html">Recent Posts</a></li>
</ul>
</nav>
js
(function() {
current_page = window.location.href;
navlinks = document.getElementsByClassName("nav-link");
active_page = document.getElementsByClassName("nav-link-active")[0];
if (active_page) {
active_page.classList.remove("nav-link-active");
}
for (i=0; i < navlinks.length; i++) {
if (navlinks[i].href == current_page) {
navlinks[i].classList.add("nav-link-active");
break;
}
}
})();
I know this is late answer but this works ok for me
var links = document.querySelectorAll('li a');
for (link of links) {
if (window.location.pathname == link.getAttribute('href')) {
link.classList.add('active')
} else {
link.classList.remove('active')
}
}
Below is the solution to add the dynamic active class to the navbar elements.
// first lets get all the navbar elements.
const navElements = document.querySelectorAll(".list");
// creating a function of active navbar item
const activeLink = (el) => {
list.forEach((item) => {
item.classList.remove("active");
el.classList.add("active");
});
};
// attaching the event listener for each element
list.forEach((item) => {
item.addEventListener("click", () => {
activeLink(item)
});
});
I'm trying to create a tab menu. And I need this coded in regular javascript, not jquery.
$(document).ready(function() {
//When page loads...
$(".general_info_content").hide(); //Hide all content
$("ul.general_info_tabs li:first").addClass("active").show(); //Activate first tab
$(".general_info_content:first").show(); //Show first tab content
//On Click Event
$("ul.general_info_tabs li").click(function() {
$("ul.general_info_tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".general_info_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
The core of what you want to do is below - I'm sure there are a thousand different ways to do each task:
Remove a CSS class from an element:
var classes = document.getElementById([id]).className.split(" ");
for(var i = 0; i < classes.length; i++)
if(classes[i] == removeClass)
classes[i] = "";
document.getElementById([id]).className = classes.join(" ");
Add a CSS class to an element:
document.getElementById([i]).className += " " + addClassName;
Hide an element:
document.getElementById([i]).style.display = "none";
Fade an element:
// not tested, but based on tested/used code
function fade(el, opacity, fadeInTime) {
if (opacity < 100) {
el.style.opacity = opacity / 100;
el.style.filter = "alpha(opacity=" + opacity + ")";
opacity += 5;
setTimeout(function () { fade(el, opacity, fadeInTime); }, fadeInTime / 5);
}
}
To find all elements by CSS and tag name:
var matches = new Array();
var all = document.getElementByTagName(searchTagName);
for(var i = 0; i < all.length; i++){
if(all[i].className.replace(searchClassName, "") != all[i].className) {
matches.push(all[i].className);
}
}
// do something with (i.e., return or process) matches
And for the record, I find it encouraging, not unreasonable, that a person using the jQuery library wants to know how to do get things done with native JS/DOM.
More functions to complement Brian's post. Good luck.
EDIT: As I mentioned I would change the class=general_info_content to id=general_info_content1.
function attach(el, event, fnc) {
//attach event to the element
if (el.addEventListener) {
el.addEventListener(event, fnc, false);
}
else if (document.attachEvent) {
el["on" + event] = fnc; // Don not use attachEvent as it breaks 'this'
}
}
function ready() {
// put all your code within $(function(){}); here.
}
function init() {
attach(document, "readystatechange", function () {
if (document.readyState == "complete") {
ready();
}
});
}
I have these links:
<a class="active" href="#section1">Link 1</a>
Link 2
When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:
Link 1
<a class="active" href="#section2">Link 2</a>
This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.
How can this be done with JavaScript/Prototype?
Try this:
// initialization
var links = document.links;
for (var i=0; i<links.length; ++i) {
links[i].onclick = function() {
setActive(links, this);
};
}
function setActive(links, activeLink) {
for (var i=0; i<links.length; ++i) {
var currentLink = links[i];
if (currentLink === activeLink) {
currentLink.className += " active";
} else {
currentLink.className = currentLink.className.split(/\s+/).map(function(val) {
return val === "active" ? "" : val;
}).join(" ");
}
}
}
You could write a little helper function with prototype support that removes the class from all active elements and adds it to the one that was clicked on:
function active(e) {
$$('.active').each(function(i) {
i.removeClassName('active');
});
e.addClassName('active');
};
You can than call this function from your onclick events:
a
b
c
If it were jQuery, I would do it like
$(document).ready(
function(){
$("a").click(function(){
$("a").toggleClass("active");
});
}
)