Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Global Event Listener [duplicate]

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?

like image 334
user3695709 Avatar asked May 31 '14 21:05

user3695709


1 Answers

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
});
like image 170
Travis J Avatar answered Dec 16 '22 23:12

Travis J