Skip to content
Advertisement

How to set a css class to an array of tags on mouse hover in Javascript?

I’ve written a little JS code to change the classname on hover.
I know it can be done with CSS, but this is just for my own knowledge.
Plus, I want to add a transition effect.
This is the code I came up with, although it’s not working.

    window.onload = function() {
        var links = document.getElementsByTagName("a"); //Getting ALL of the <a> tags
        for(var i = 0; i < links.Length; i++) { // 'looping' through the array 'links'
            links[i].onmouseover = function() { links[i].setAttribute("class,"a_hover"); } // for every var(is this right?) in the array (a.k.a each <a> tag), set class = "a_hover".
        }
    }

It might be because I set the styling this way ; .parentDIV a though I’m not sure.

The syntax of the links: <a href="#">Home</a>

Also, as I said, I would like to add a transition animation. Like a fade-to-class kinda animation. It’d be really helpful if you could just LIST the steps to achieve it. (The answer itself would be even better, though I won’t understand/learn a thing so it doesn’t really do the job :P)

P.S; Yea, I’m new to Javascript.

Advertisement

Answer

  1. links.Length IMHO should be length (small letter)
  2. this.setAttribute(“class”,”a_hover”); (use this, there was a missing ‘”‘)

    window.onload = function() {
    links = document.getElementsByTagName("a"); //Getting ALL of the <a> tags
    for(var i = 0; i < links.length; i++) { // 'looping' through the array 'links'
        links[i].addEventListener("mouseover", function() { this.className = "a_hover"; }, false);
    } }​
    

css:

​.a_hover{color:red}​
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement