3zzy 3zzy - 1 year ago 135
Javascript Question

Combine hover and click functions (jQuery)?

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


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


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

can they be combined into one function?


Answer Source

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

Second way: use bindon:

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