ttI have two functions like so:
function fn1() {
$(".element").append("<div class='trigger'></div>");
}
function fn2() {
$(".element").append("<div class='trigger'></div>");
}
and one listener:
$(".trigger").click(function() {
// do some magic with $(this) element
});
The problem is that if click event listener is located outside fn1 and fn2 it doesn't see when dynamically created element (trigger) is clicked.
How can I make event listener to listen globally?
jsFiddle Demo
Delegate the click handler to all current and future instances of .trigger
using on
$("body").on("click",".trigger",function() {
// do some magic with $(this) element
});
edit
jsFiddle Demo
Re: Could you also advise how to create hover listener with on statement please?
Hover is indeed a corner case here. With the fluent approach you could use $().hover(function(){},function(){})
. However, this is not the case with using on
. In order to use it with on you actually have to use two separate delegations with mouseenter
and mouseleave
$("body").on("mouseenter",".trigger",function() {
// do some magic with $(this) element
});
$("body").on("mouseleave",".trigger",function() {
// do some magic with $(this) element
});
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