jQuery Mouseover Mouseout Combined Function

If you are looking for an easier way of writing your jQuery mouseover/mouseout actions, did you know you can combine them into a single handler?

Let’s say you have this code:

$(‘.my-btn’).mouseover (function() {
$(this).fadeOut();
$(‘#hidden-panel’).slideUp();
});
$(‘.my-btn’).mouseout (function() {
$(‘#hidden-panel’).slideDown();
.delay(1000);
$(this).fadeIn();
});

To simplify it, you can use the hover action and combine the mouseover/out events like this:

$(‘.my-btn’).hover (function() {
$(this).fadeOut();
$(‘#hidden-panel’).slideUp();
}, function() {
$(‘#hidden-panel’).slideDown();
.delay(1000);
$(this).fadeIn();
});

Remember, $(this) refers to the element itself, in this case, the element with the class of .my-btn attached to it.

This is a great trick for adding and removing classes from elements such as divs and table rows. To do that, modify the code above like this:

$(‘.my-div’).hover (function() {
$(this).addClass(‘div-hover’);
}, function() {
$(this).removeClass(‘div-hover’);
});

other page


What do you think?

It's good to talk!

Your email address will not be published.