Ben Lee
Ben Lee

Reputation: 53349

In jQuery what's the best way to add a class on mouseover and remove it on mouseout?

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?)

Upvotes: 3

Views: 439

Answers (4)

Sarah Groß
Sarah Groß

Reputation: 10879

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?

Upvotes: 1

Kristoffer Svanmark
Kristoffer Svanmark

Reputation: 788

Or:

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

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 238065

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

$(elem).hover(function() {
    $(this).toggleClass('hover');
});

Upvotes: 6

dknaack
dknaack

Reputation: 60556

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

Upvotes: 10

Related Questions