Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate hover using JavaScript events

Is it possible to simulate hover using JavaScript Events? I tried injecting mouseover event on the target element but no luck.

For example, if there is a link that has a hover selector, is it possible to "hover" over it using JavaScript Events? Basically, I want to trigger CSS hover. You can assume I can't use jQuery.

like image 585
bellpeace Avatar asked Jul 30 '12 19:07

bellpeace


2 Answers

The jQuery hover event is just using mouseenter and mouseleave events. Here is the source of jQuery's hover:

function (fnOver, fnOut) {
    return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
}
like image 190
Tim Banks Avatar answered Oct 09 '22 00:10

Tim Banks


Yes, you would simply add onMouseOver and onMouseOut events to the element in question

Like this:

<div class="something" onmouseover="hover(this);" onmouseout="unhover(this);">

Then make your javascript change the element's class (if you want two different CSS classes) or simply modify the element's style directly. You could do something like this.

<script>
function hover(element) {
    element.setAttribute('class', 'something hover');
}
function unhover(element) {
    element.setAttribute('class', 'something');
}
</script>

Please note that you can also use a library like jQuery to handle this even more simply.

like image 37
Mike Brant Avatar answered Oct 09 '22 01:10

Mike Brant