It seems this subject is recurring, but sorry, I can’t really find any answer to my problem.
I’m using jQuery to update a div content with Ajax.
This update is triggered by items inside the updated div.
$(function() {
$(".add").on('click',function(){
$("#table").load("displayTable.php");
});
// just to see if I can update the DOM...
$('input').on('click',function(){
$(this).css("background","red");
});
});
Html:
<div id="table">
<input type="text" />
<a class="add">Add</a>
</div>
As DOM is not updated, jQuery functions only work with the original #table, not the ajax-loaded one.
I’ve not really well understood how to use on(), as I guess this would be the solution to update the listener…
Thanks for your help 🙂
Let’s start by defining a couple of terms. The element where the event handler is bound is called the capturing element. The element where the event originates (so, the element that was clicked) is the originating element.
These elements do not have to be the same, because events in Javascript bubble, that is to say, all ancestor elements of the originating element are notified of the event. So you can handle the event on any of the ancestor elements. This is called event delegation.
The
onmethod is a nice way of doing event delegation. The element in the original selection is the capturing element: the event handler will be bound to this element. If this element always exists – i.e. it is not replaced by AJAX – you can be sure that all events will be handled by this handler, even if they originated on elements that don’t exist yet.The simplest form of
ononly has one selector, which is treated as both the originating element and the capturing element:The handler is bound to all
inputelements, and events that originate oninputelements are handled by it. However, onlyinputelements that existed when the handler was bound will have the handler bound, so this isn’t much good for you.There is another syntax, with an additional selector. This allows you to specify both the element where the handler is bound and also another selector that specifies where it must originate. In this case,
#tablewill always exist, so we can bind to that:This says, “bind an event handler to
#table, but only activate it if the event was a click on aninputelement”.