74

Please, considere this CSS code:

a { color: #ffcc00; }
a:hover { color: #ccff00; }

This HTML code:

<a href="#" id="link">Link</a>
<button id="btn">Click here</button>

And, finally, this JS code:

$("#btn").click(function() {
   $("#link").trigger("hover");
});

I would like to make my link uses its pseudo-class :hover when the button is clicked. I tried to trigger events like mousemove, mouseenter, hover etc, but anyone works. Notice that I want to force the use of the my CSS pseudo-class :hover specification and not use something like:

$("#link").css("color", "ccff00");

Some one know how do I do this? Thank you a lot.

Sampson
  • 265,109
  • 74
  • 539
  • 565
MCardinale
  • 1,408
  • 2
  • 15
  • 22

3 Answers3

121

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

Sampson
  • 265,109
  • 74
  • 539
  • 565
36

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

Mike
  • 385
  • 3
  • 2
  • 5
    fwiw, I have found that this will not load images if there is a style rule for :hover that specifies a background image. – jrz Jun 13 '12 at 20:22
  • 16
    mouseover is different from CSS :hover. So this won't work. It can only work in situation where a mouseover event has been bound on something. – Kushagra Gour Jun 23 '13 at 12:20
  • Funny enough i kept trying different ways to add classes but this did solve my issue... its useful answer under circumstances. – joshua Jun 23 '14 at 04:32
  • I think this method is better then the one above as it does not require another class to be added to change the elements style. – Digggid Aug 16 '18 at 18:15
0

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

Digggid
  • 297
  • 2
  • 10