Dan Davies{ Front-end Developer }

Adding an active class to a menu

6th April 2013

If you have ever wanted to have an active state on a menu item and you don’t know how to do it and your platform doesn’t do it by default (Like WordPress), here is some javascript that works.

function scriptInit() {
if (!document.getElementById) {
	return;
	}
}
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
	elm.addEventListener(evType, fn, useCapture);
	return true;
	} else if (elm.attachEvent) {
	var r = elm.attachEvent('on' + evType, fn);
	return r;
	} else {
	elm['on' + evType] = fn;
	}
}
function checkActive() {
	var a = document.getElementsByTagName("a");
	if (window.location.href.substr(location.href.length - 1, 1) == '/') {
		var loc = window.location.href + 'index.html'; 
	}
	else {
		var loc = window.location.href;
	}
	for(var i=0; i < a.length; i++) {
		if (a[i].href == loc) {
			a[i].setAttribute("class", "active");
			a[i].setAttribute("className", "active");
		}
	}
}
addEvent(window, 'load', checkActive, false);

You just need to create styles for the .active class now

.active
    {
        text-decoration: underline;
    }

Of course I am sure if you are good with javascript, you could probably strim this down a bit but this is a starter for someone who is looking to do it and doesn't know how.

Back to top