Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger the css:hover event with js

I have <div class="animate"> and in css:

div.animate:hover{
//do stuff
}

But would also like to invoke this via javascript.

Is it possible?

like image 629
dukevin Avatar asked May 21 '12 06:05

dukevin


2 Answers

As described in Trigger css hover with JS this is not possible as-is (if you want it as described exactly at the time of the creation of this answer).

But the main goal is achievable by:

  1. Setting a class hover (or whatever name) as well as the selector :hover in the CSS.
  2. Calling .addClass("hover") to trigger CSS, and .trigger("hover") or .trigger("mouseenter") to trigger the JS.
  3. Ensuring the mouseleave handler. or 2nd .hover() handler, clears the hover class if present.
like image 89
Meligy Avatar answered Nov 14 '22 20:11

Meligy


Instead of doing it this way, I suggest you just add a class to the other tag. In jQuery it would be:

 $(window).load(function() {
    $('.trigger-animate').hover(function(){
        $('.animate').addClass('hover');
    });
}

I'd recommend using this method, because it handles both onMouseOver and onMouseOut (this way you can also remove the class when your mouse leaves $('.trigger-animate') if you so desired using this syntax:

.hover( handlerIn(eventObject), handlerOut(eventObject) )
 checking out the documentation
like image 1
evancohen Avatar answered Nov 14 '22 20:11

evancohen