I'm trying to get used to the new proper way of doing things in jQuery but I can't figure out how to do a "live" binding that's as elegant/DRY as the original. Previously, with "live" I believe you could do this, only mentioning the element once:
$("#element_id").live("click",function(){
//stuff
}).live("mouseover", function(){
//stuff
}).live("mouseout", function(){
//stuff
});
Now, with $(document).on
it seems I would need to do this:
$(document).on("click","#element_id",function(){
//stuff
}).on("mouseover","#element_id",function(){
//stuff
}).on("mouseout","#element_id",function(){
//stuff
});
This is less concise and repeats the element. Is there an obviously simpler way to achieve this?
The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.
You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
JQuery's bind allows multiple events, like so: $(window). bind('mousemove touchmove', function(e) { //do something; });
The mouseenter() Method The jQuery mouseenter() method attach an event handler function to the selected elements that is executed when the mouse enters an element.
$(document).on({
click: function () {},
mouseover: function () {},
mouseout: function () {}
}, '#element_id');
Beware of using document
; you may want to use a more specific selector. Also I wouldn't necessarily say it's bad practice to have an ID element loaded dynamically, but it looks suspicious.
I find this approach useful if your callbacks need to share code:
var handler = function ( event ) {
var $target = $( event.target );
if ( $target.is( '#element_id' ) ) }
switch ( event.type ) {
case 'click':
// stuff
break;
case 'mouseenter':
// stuff
break;
case 'mouseleve':
// stuff
break;
}
}
};
$( document ).on({
click: handler,
mouseenter: handler,
mouseleave: handler,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With