Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript addEventListener - using to create a mouseover effect?

Tags:

I have a div with an id of "button". I am trying to change its background to become blue when I hover (without using the CSS hover selector).

var item = document.getElementById("button"); item.addEventListener("mouseover", func, false);  function func() {      var item = document.getElementById("button");    item.setAttribute("style", "background-color:blue;") } 

This, however, only sets the color of the item to blue when I hover, but does not reset it to white after I move mouse away. How can I correct this? (btw, mouseenter and mouseleave do not work with this seemingly).

like image 585
antonpug Avatar asked Nov 29 '11 22:11

antonpug


2 Answers

You will need to setup a similar event to handle mouseout. Inside the mouseout event function, you can change the color back to the original color.

var item = document.getElementById("button"); item.addEventListener("mouseover", func, false); item.addEventListener("mouseout", func1, false);  function func() {  // not needed since item is already global,     // I am assuming this is here just because it's sample code?    // var item = document.getElementById("button");     item.setAttribute("style", "background-color:blue;") }  function func1() {      item.setAttribute("style", "background-color:green;") } 
like image 165
AndrewR Avatar answered Sep 28 '22 03:09

AndrewR


Have you tried mouseout?

(Unfortunately the event "mouseover" was poorly named - it would've been better if it had been called "mousein" so that it was more obviously and intuitively the opposite of "mouseout". But that's just one of many inconsistent event things.)

I think mouseenter and mouseleave are IE things that other browsers may not support - though I think jQuery supports those events too.

like image 34
nnnnnn Avatar answered Sep 28 '22 05:09

nnnnnn