45

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!

eozzy
  • 66,048
  • 104
  • 272
  • 428

8 Answers8

105

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
});
saber tabatabaee yazdi
  • 4,404
  • 3
  • 42
  • 58
Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
29

Use mouseover instead hover.

$('#target').on('click mouseover', function () {
    // Do something for both
});
Vergilius
  • 291
  • 3
  • 3
9
$("#target").hover(function(){
  $(this).click();
}).click(function(){
  //common function
});
9

You can use .bind() or .live() whichever is appropriate, but no need to name the function:

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

or if you were doing this on lots of element (not much sense for an IE unless the element changes):

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

Note, this will only bind the first hover argument, the mouseover event, it won't hook anything to the mouseleave event.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1
var hoverAndClick = function() {
    // Your actions here
} ;

$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;
St.Woland
  • 5,357
  • 30
  • 30
1

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});
PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
  • A heads up for any future readers not already aware 'As of jQuery 3.0, `.bind()` has been deprecated. It was superseded by the `.on()` method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.' http://api.jquery.com/bind/ – Hastig Zusammenstellen Sep 14 '16 at 12:08
0

i think best approach is to make a common method and call in hover and click events.

Adeel
  • 19,075
  • 4
  • 46
  • 60
0
  $("#target").on({
        hover: function(){
           //do on mouse hover
        },  
        click: function(){
            //do on mouse click
        }  
    });
Suhani Mendapara
  • 297
  • 1
  • 3
  • 10
  • When giving an answer it is preferable to give [some explanation as to WHY your answer](http://stackoverflow.com/help/how-to-answer) is the one. – Stephen Rauch Feb 23 '17 at 14:15