Event for highlighting the hovered element?
I'm currently using this code to bind events in a Google Chrome extension:
var bindEvent = function(elem ,evt,cb) {
//see if the addEventListener function exists on the element
if ( elem.addEventListener ) {
elem.addEventListener(evt,cb,false);
//if addEventListener is not present, see if this is an IE browser
} else if ( elem.attachEvent ) {
//prefix the event type with "on"
elem.attachEvent('on' + evt, function(){
/* use call to simulate addEventListener
* This will make sure the callback gets the element for "this"
* and will ensure the function's first argument is the event object
*/
cb.call(event.srcElement,event);
});
}
};
/* ... */
bindEvent(document,'click', function(event)
{ var target = event.target || event.srcElement;
/*Code to do stuff about a clicked element*/
this.removeEventListener('click',arguments.callee,false);
});
And it works well with the click event. Now, my question is: what event could I use to change something about an element being hovered and not simply clicked on? The final goal would be to change the background color of the element being hovered by the cursor.
I tried mouseover
, mouseenter
, focus
and focusin
to no avail. To be exact, I tried to do a console.log()
when the event triggers, but it never really happened, except one time when I clicked on a dialog box and it detected my focus on this element.
I currently am using Chrome (v24.0), but a cross-browser solution would be a nice feature because I plan to reuse the script on Firefox later. It's not a top priority though.
The relevant events for hovering are mouseover
and mouseout
- they are triggered when the mouse enters or leaves an element respectively. However, since that event is also triggered for the child elements of the element you attached your listener on and these events bubble up, you also have to check event.target
:
elem.addEventListener("mouseover", function(event) {
if (event.target == elem) {
// Mouse pointer entered elem
}
}, false);
elem.addEventListener("mouseout", function(event) {
if (event.target == elem) {
// Mouse pointer left elem
}
}, false);