jQuery Global Event Listener
javascript, jquery
Solution
`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
});
Problem
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?