7

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?

dukevin
  • 22,384
  • 36
  • 82
  • 111
  • 1
    Have you looked here http://stackoverflow.com/questions/2228376/trigger-onmouseover-event-programatically-in-javascript ? – sleepwalker May 21 '12 at 06:34
  • 1
    possible duplicate of [Trigger css hover with JS](http://stackoverflow.com/questions/4347116/trigger-css-hover-with-js) – Joseph May 21 '12 at 06:35
  • possible duplicate of [Hover Item with JQuery](http://stackoverflow.com/questions/1983169/hover-item-with-jquery) – kapa May 21 '12 at 06:38

2 Answers2

6

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.
Community
  • 1
  • 1
Meligy
  • 35,654
  • 11
  • 85
  • 109
1

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
evancohen
  • 677
  • 1
  • 5
  • 9
  • I'm new to jQuery, would this go in the "onMouseOver" ? If not, where would I put this code – dukevin May 21 '12 at 06:45
  • Put it in $(window).load -------- .hover is a replacement for onMouseOver, so you don't even need it! – evancohen May 21 '12 at 11:30
  • Sorry, I'm still lost. Where do I put the .hover(...) in your second code snippet – dukevin May 22 '12 at 22:10
  • The second snippet is just just the full syntactical documentation for the first. All you would need is the first one, and you could add a second function using the syntax of the second to handle when the mouse moves out. Hope that clears things up a bit. – evancohen May 30 '12 at 17:54
  • is there no way to do this with vanilla JS? – oldboy Jan 07 '19 at 22:48