how can I apply a jquery function to elements that are loaded with ajax?
<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
....
<span class="h">Test</span><br /><br />
<script type="text/javascript">
$(document).ready(function() {
$('.h').click(function() {
alert("test");
});
});
</script>
So, this works perfectly. Every click on a span element returns an alert. But there the click function is not applied to the elements loaded with ajax:
<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
<span class="h">Test</span><br /><br />
....
<span class="h">Test</span><br /><br />
<script type="text/javascript">
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('body').append('<span class="h">Test3</span><br /><br />');
}
});
$(document).ready(function() {
$('.h').click(function() {
alert("test");
});
});
</script>
How can I solve that issue?
You aren't reapplying the behaviour. You need to use jQuery's live method to keep checking the DOM for new elements.
Demonstration of live
You must use live instead of click, so that the event is binded also to newly appended items:
You need the
live
function to bind the event to elements created dynamically:The
click()
function only adds a listener to the elements present at th time it was called. You need to call it again on any element, you add later on.Or, as @jerluc stated, use the
live()
function.jQuery's
live()
is what you'll want: