How to create the issue:
- click on existing trigger links - something happens (pass)
- click on the "add trigger" button, which appends a new trigger link w/ same class
- click on the newly created link, and it does not do the same thing as the 1st 2 links that existed from the start (fail)
Here is my example -: http://jsbin.com/equjig/3/edit
I thought the .on('click', func)
function was good for adding events to current elements in the dom, but also for future elements that get added to the dom?
Here is my current javascript :
$(document).ready(function() {
$(".link").on('click', function(e) {
e.preventDefault();
$("#out").append("clicked<br/>");
});
$("#b1").on('click', function() {
$("#p1").append("<a href='#' class='link'>new trigger</a>");
});
here is the HTML
<button type="button" id="b1">add trigger</button>
<p id="p1">
<a href="#" class="link">trigger 1</a>
<a href="#" class="link">trigger 2</a>
</p>
<div id="out"></div>
Note - im using jQuery 1.7
Thanks!
Change the .on() to .live()
You are almost there with on ...
working example : http://jsbin.com/equjig/6/edit
This will work - you should select a parent div of the
.link
elements (i have used$('#p1')
here, like in your jsbin)You can use
.on()
from version 1.7, and it also somewhat replaces the old.live()
except in how you provide the syntax.Using
.on()
you can delegate the event to any parent element like this:This way, it will also work for future elements that are added inside the body that has the className '
link
'.I made a small modification to your lint that works the way you expect: http://jsbin.com/adepam. And here is the code:
.on()
can also behave like.delegate()
which is used like this:Here's documentation for
.on()
: http://api.jquery.com/onAccording to the api docs for
on
the signature.on('click', func)
replicates.bind
's behaviors - that is to say, it binds the listener to each and every existing element in the collection.To get
.delegate
behaviors - that is, to bind to each and every event that originates from a specific kind of (child) element, include a selector:The
onclick
event applied only to the elements that already exist. You need to use.live
function.