eozzy
eozzy

Reputation: 68670

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!

Upvotes: 45

Views: 152059

Answers (8)

Emil Ivanov
Emil Ivanov

Reputation: 37633

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
});

Upvotes: 106

Suhani Mendapara
Suhani Mendapara

Reputation: 307

  $("#target").on({
        hover: function(){
           //do on mouse hover
        },  
        click: function(){
            //do on mouse click
        }  
    });

Upvotes: 0

Vergilius
Vergilius

Reputation: 291

Use mouseover instead hover.

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

Upvotes: 29

Nick Craver
Nick Craver

Reputation: 630419

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.

Upvotes: 9

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

Upvotes: 1

user241244
user241244

Reputation:

$("#target").hover(function(){
  $(this).click();
}).click(function(){
  //common function
});

Upvotes: 9

St.Woland
St.Woland

Reputation: 5417

var hoverAndClick = function() {
    // Your actions here
} ;

$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;

Upvotes: 1

Adeel
Adeel

Reputation: 19228

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

Upvotes: 0

Related Questions