Insert tags that were not seen by jQuery
Let's say I have this code in my page:
<script language="javascript">
$(document).ready(function() {
$(".test").click(function() {
alert('Hello');
});
});
</script>
Why does the previous code not apply to elements with class "test" that I add later in the document, for example, for example:
$('body').append('<p class="test">Test</p>');
Because what happens is that when I click the previous tag <p>
, nothing happens.
Also, if I have this:
<div id="first">Edit me.<div id="second">Save me.</div></div>
Can I do what the text describes? those. controlling div content #first
without affecting #second
div content ?
Thank.
The problem is that .click()
it only applies a listener to the elements available in the DOM when the method is executed. Instead, you should take a look at .on()
.
With the help .on()
you can delegate the event, for example this:
$("body").on("click", ".test", function() {
alert('Hello');
});
Now any element (current and future) with a class test
available in your body will have a listener for click events.
live has been deprecated since 1.7, use
http://api.jquery.com/on/
try using on () listener:
$(document).on("click",".test", function() {
alert('Hello');
});
When you bind events to elements, they only bind to the elements that have already been created. Therefore, you need to run bind command again on new items.
Alternatively you can use on('click')
which will bind the event to existing and all future items.
Because at the time you attach your event handler, the object doesn't exist yet. You cannot subscribe to items that don't exist. You can use the Live method for this.
http://api.jquery.com/live/
They seem to be outdated (thanks to @Anthony Grist). Use On or delegate () instead.
http://api.jquery.com/on/
http://api.jquery.com/delegate/
$('div').on('click', function()
{
//Do something
});
you must use "on" to bind events with elements that are added after the script is interpreted.
$(document).on("click", selector, function(e){
//do something
});
If you need to apply tags added later, you must use live in
$(document).on('click','.test',function() { });
EDIT: @ Anthony you are right. live is deprecated. Updated code