5

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?

user3695709
  • 53
  • 1
  • 3

2 Answers2

10

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
});
Travis J
  • 77,009
  • 39
  • 185
  • 250
  • this didn't work, still doesn't see the click event. The problem only persists because new element is created inside function. If I put listener inside function too then it can see the click event – user3695709 May 31 '14 at 21:57
  • @user3695709 - There must be something else affecting your code. Do you see any errors in your console? Look at this jsfiddle demo: http://jsfiddle.net/qPYLh/ It demonstrates this approach working. – Travis J May 31 '14 at 22:01
  • Sorry, it was my mistake. Could you also advise how to create hover listener with on statement please? – user3695709 May 31 '14 at 22:10
  • @user3695709 - Sure, see edits. – Travis J May 31 '14 at 22:15
0

Try this:

$("body").on("click", ".trigger", function() {
// do some magic with $(this) element
});
Nept
  • 103
  • 1
  • 10
  • 1
    What does this do? Why does it solve the OP's problem? Please **explain** your solution (and the problem). – Felix Kling May 31 '14 at 22:18
  • Because the trigger class is added to the dom after loading. It is therefore re-check the DOM in some way, so find the famous class and trigger the corresponding event when clicked. – Nept May 31 '14 at 22:27
  • 1
    This doesn't recheck the DOM, the event is bound to `body` and when `body` hears the click it delegates the event to `.trigger`, so if `.trigger` is the target or an ancestor of the target, the event will be executed. – Popnoodles May 31 '14 at 22:50