Question

Combine hover and click functions (jQuery)?

Can hover and click functions be combined into one, so for example:

click:

$('#target').click(function() {
  // common operation
});

hover:

$('#target').hover(function () {
    // common operation
});

can they be combined into one function?

Thanks!

 45  151530  45
1 Jan 1970

Solution

 106

Use basic programming composition: create a method and pass the same function to click and hover as a callback.

var hoverOrClick = function () {
    // do something common
}
$('#target').click(hoverOrClick).hover(hoverOrClick);

Second way: use bindon:

$('#target').on('click mouseover', function () {
    // Do something for both
});

jQuery('#target').bind('click mouseover', function () {
    // Do something for both
});
2010-03-12

Solution

 29

Use mouseover instead hover.

$('#target').on('click mouseover', function () {
    // Do something for both
});
2013-12-09