Manish Mathe
Manish Mathe

Reputation: 51

Trigger hover with jQuery?

How do I achive this

$("#a").parent().trigger('hover')

with jQuery? The code is not working for me.

Upvotes: 1

Views: 9201

Answers (3)

Anders
Anders

Reputation: 8588

As pointed out by TJ Crowder and Endel, this can not be done directly. However, you can achieve the effect of the span having the hover style applied to it by adding a class.

First, change your CSS so it looks like this:

#text:hover, #text.hovered
{
    /* Your styles. */
}

That means that the same styles will be applied to text when it is hovered and when it has the class hovered. Then just add the class whenever you want to have the hover affect:

$("#a").parent().addClass('hovered');

And remove it when you no longer want it:

$("#a").parent().removeClass('hovered');

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075735

Two different answers depending on what you're really asking:

If you've hooked up a handler using hover and are trying to trigger it.

From the documentation:

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

So if you want to trigger the handler for mouseenter, trigger mouseenter. If you want to trigger the handler for mouseleave, trigger mouseleave.

Note, though, that generally it's better just to call your function directly than to call it indirectly by triggering the event.

If you're trying to trigger the CSS for an element being "hovered"

...you can't. Instead, define a class that does the same thing, and add that class to the element.

Upvotes: 3

Endel Dreyer
Endel Dreyer

Reputation: 1654

There is no way to force a fake "hover" event in the DOM.

If you just want to change the appearance of the button, add a class to it instead.

Upvotes: 0

Related Questions