I am writing some vanilla JavaScript to create a nice navigation menu. I am stuck on adding an active class.
I am getting elements by class name NOT by id. The belo
In your snippet, button
is an instance of NodeList
, to which you can't attach an event listener directly, nor can you change the elements' className
properties directly.
Your best bet is to delegate the event:
document.body.addEventListener('mouseover',function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
{
target.className += ' active';//set class
}
},false);
Of course, my guess is that the active
class needs to be removed once the mouseout
event fires, you might consider using a second delegator for that, but you could just aswell attach an event handler to the one element that has the active
class:
document.body.addEventListener('mouseover',function(e)
{
e = e || window.event;
var oldSrc, target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
{
target.className += ' active';//set class
oldSrc = target.getAttribute('src');
target.setAttribute('src', 'images/arrows/top_o.png');
target.onmouseout = function()
{
target.onmouseout = null;//remove this event handler, we don't need it anymore
target.className = target.className.replace(/\bactive\b/,'').trim();
target.setAttribute('src', oldSrc);
};
}
},false);
There is some room for improvements, with this code, but I'm not going to have all the fun here ;-).