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?
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) {
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