Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 571
eozzy Avatar asked Mar 12 '10 10:03

eozzy


People also ask

How do you click on hover?

You can click or drag simply by hovering your mouse pointer over a control or object on the screen. This is useful if you find it difficult to move the mouse and click at the same time. This feature is called Hover Click or Dwell Click.

Is hover () a jQuery event method?

The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element.

Is hover deprecated in jQuery?

fn. hover() is deprecated #66.

What does the hover function in jQuery do?

Definition and Usage The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.


2 Answers

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
});
like image 107
Emil Ivanov Avatar answered Oct 22 '22 00:10

Emil Ivanov


Use mouseover instead hover.

$('#target').on('click mouseover', function () {
    // Do something for both
});
like image 29
Vergilius Avatar answered Oct 21 '22 23:10

Vergilius