Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching event to future elements using jquery [duplicate]

I am using jquery 1.8 and have to display popup when user clicks some area with class dropdown-toggle. I have attached the events using on while the page loads for the first time.

Here is it

$('.dropdown-toggle').on("click", function (e) {
console.log("dropdown toggle called");
$(this).next('.dropdown').toggle();
});
$(document).on("click", function (e) {
var target = e.target;
console.log("click toggle called");
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});

What i found that second event applies to elements added in future but the first one does not i.e. for a drop down menu added later, only "click toggle called" gets printed in console but for those elements added during start both "click toggle called" and "dropdown toggle called" gets printed.

What is problem here? Does on applies only to document for future element or can it be applied to class or other elements too so that they apply to future elements? If not what is the solution?

like image 425
Sumit Shrestha Avatar asked Feb 03 '14 08:02

Sumit Shrestha


1 Answers

You can use delegation with .on(). This way it will listen for a click in document (it could also be a parent of your element, as long as its present when the event handler is run), when fired look for the element specified as a parameter of the .on().

Try this:

$(document).on("click", '.dropdown-toggle', function (e) {
like image 65
Sergio Avatar answered Sep 23 '22 07:09

Sergio