1

All the examples i found online didn't work for me. All i want is to change color on text when mouse is on it. And when move mouse to get old color (and maybe to change size, but if that is too complicated not yet) I know how to do that in CSS but i am learning JS and thats the way i would like it. It is only one word in text so it is Class and not ID.

document.getElementsByClassName("akcija").addEventListener("mouseover", mouseOver);
document.getElementsByClassName("akcija").addEventListener("mouseout", mouseOut);
function mouseOver() {
    document.getElementsByClassName('akcija').style.color = "black";    
}
function mouseOut() {
    document.getElementsByClassName('akcija').style.color = "Blue";    
}
<div class="akcija" style="width:200px; height:200px"></div>
Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
  • `getElementsByClassName` returns a collection. – SLaks Apr 20 '17 at 18:31
  • 1
    Possible duplicate of [addEventListener on NodeList](http://stackoverflow.com/questions/12362256/addeventlistener-on-nodelist) – Andreas Apr 20 '17 at 18:32
  • Possible duplicate of [JavaScript click event listener on class](http://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class) – Rick Hitchcock Apr 20 '17 at 18:34
  • Thank you. I was searching with "onmouseover" and didn't found solution. I didn't know that getElementByClassName is a problem and that i should search for it. Thanks – nnikolic1986 Apr 20 '17 at 18:37

2 Answers2

0

document.getElementsByClassName method returns a nodeList, so, you can access a DOM element using its index (zero-based).

Try this:

document.getElementsByClassName('akcija')[0].style.color = "black";

If you are using ES6 you could do this using Array.from method.

Array.from(document.getElementsByClassName('akcija')).forEach(function(element) {
  element.addEventListener('mouseover', mouseOver);
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

Correct code implement IMHO

var akcjijas = document.getElementsByClassName("akcija");

for (var i in akcjijas) {
    if (akcjijas.hasOwnProperty(i)){
        akcjijas[i].addEventListener("mouseover", mouseOver);
        akcjijas[i].addEventListener("mouseout", mouseOut); 
    }
}
   
function mouseOver() {
    this.style.color = "black";    
}
function mouseOut() {
    this.style.color = "Blue";    
}
<div class="akcija" style="width:200px; height:100px;background-color: yellow">Akcija</div>
Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
  • Thank you very much. It is great. I tried a lot of stuff myself but they never worked. Now it is much clearer for me how to set something up. – nnikolic1986 Apr 20 '17 at 18:49