3

Is there a jQuery shortcut for this?

$(element).on("mouseover", function() {
    $(this).addClass("hover");
}).on("mouseout", function() {
    $(this).removeClass("hover");
});

I see in the jQuery docs a method called hover(), but that seems to bind on events mouseenter and mouseleave (should I be using those events instead of mouseover and mouseout?)

Ben Lee
  • 52,489
  • 13
  • 125
  • 145

4 Answers4

10

Description

You can user jQuery's hover() method.

Check out the sample and this jsFiddle Demonstration

Sample

$(elem).hover(function(ev) {
    $(this).addClass('hover');
}, function(ev) {
    $(this).removeClass('hover');
});

More Information

dknaack
  • 60,192
  • 27
  • 155
  • 202
6

The simplest way, to remove duplication of code, is by passing one argument to hover and use toggleClass:

$(elem).hover(function() {
    $(this).toggleClass('hover');
});
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Will this definitely always work? Is there any way the "toggle state" might get out of sync? – Ben Lee Jan 12 '12 at 20:46
  • you take a risk, because you don't know what was the initial state. – gdoron Jan 12 '12 at 20:46
  • @BenLee Only if you are toggling it with some other bit of code, which seems quite unlikely/foolish. – lonesomeday Jan 12 '12 at 20:46
  • @gdoron, assuming I do know the initial state. I just want to make sure there are no edge cases (like the cursor going from "over element" to "outside browser window" to "not over element" type deal). – Ben Lee Jan 12 '12 at 20:49
  • 3
    I voted for this AND dknaack's answers -- yes, there is a risk that toggle state can go out of sync if you're not aware of or in control of your full scenario. But if you are, it's pretty slick. But on the other hand, 3 lines vs. 5 lines... you could always go the safe route with dknaack's. – Greg Pettit Jan 12 '12 at 20:51
2

Or:

$(element).hover(function () {
    $(this).addClass("hover");
}, function () {
    $(this).removeClass("hover");
});
1

hover() is only a bit more compact:

$(elem).hover(function(ev) {
    $(this).addClass('hover');
},function(ev) {
    $(this).removeClass('hover');
});

For the difference between mouseover/mouseout and mouseenter/mouseleave, see What is the difference between the mouseover and mouseenter events?

Community
  • 1
  • 1
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50