views:

863

answers:

7

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!

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

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

Adeel
+3  A: 

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, is to use bind:

$('#target').bind('click hover', function () {
    // Do something for both
});
Emil Ivanov
A: 
var hoverAndClick = function() {
    // Your actions here
} ;

$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;
St.Woland
A: 

You could also use bind:

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

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
A: 

that's not the question he's asking for, he wants to know : if you hover an element -> the element changes to blue -> then you click it (so it should keep is blue color even if you unhover it), is that possible ?

ty