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).
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;") }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With