It is always tempting to bind your event directly but this may not work all the time. Therefore, we suggest a little trick here. Be sure that your scripts are well ordered.
Everytime we’re looking to bind an event to a selector, for instance some links, we tend to do it directly like this:
$(".example a").on("click", function(){ alert("clicked") });
This works if your element is already on the page but if you’re adding another link with another script and then place in the DOM, you’ll be out of luck.
That’s where Event delegation comes handy! The definition from the JQuery site:
“Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.”
Which means, if we want to delegate this event, we would do something like this:
$(document).on("click", ".example a", function(){ alert("clicked") });
That will always go back to the root to look what’s been added to the DOM and fire accordingly.
Hope this little trick helps you out!