Can hover and click functions be combined into one, so for example:
click:
$(\'#target\').click(function() {
// common operation
});
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 bind
on
:
$('#target').on('click mouseover', function () {
// Do something for both
});
jQuery('#target').bind('click mouseover', function () {
// Do something for both
});
$("#target").on({
hover: function(){
//do on mouse hover
},
click: function(){
//do on mouse click
}
});
You could also use bind:
$('#myelement').bind('click hover', function yourCommonHandler (e) {
// Your handler here
});
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.
i think best approach is to make a common method and call in hover and click events.
Use mouseover instead hover.
$('#target').on('click mouseover', function () {
// Do something for both
});