Reputation: 53349
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
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
Reputation: 788
Or:
$(element).hover(function () {
$(this).addClass("hover");
}, function () {
$(this).removeClass("hover");
});
Upvotes: 2
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
Reputation: 60556
You can user jQuery's hover()
method.
Check out the sample and this jsFiddle Demonstration
$(elem).hover(function(ev) {
$(this).addClass('hover');
}, function(ev) {
$(this).removeClass('hover');
});
Upvotes: 10