Being fairly new to jQuery and the AJAX basics, I've been trying to set up some fairly simple dynamic loading.
I include a .js file setting up the click
event handler, and it looks like this:
var baseurl = document.getElementById("baseurl").getAttribute("href");
var pattern = new RegExp("[^/]+");
var page = "cnt/" + pattern.exec(window.location.href.substr(baseurl.length)) + ".php";
$(document).ready(function(){
$('a.ajax').bind('click',function(event){
event.preventDefault();
$('#content').load("cnt/" + pattern.exec(this.href.substr(baseurl.length)) + ".php")
})
});
Note that I do some changes to the file so the relative href "testing/" would turn into an absolute path to the file "cnt/testing.php".
My anchor tags look like this:
<a href="testing/" class="ajax">Link to testing page</a>
My problem is, that whenever new content is loaded into div#content the handler in my .js file is not registered for any links that may have appeared using AJAX. In other words the links will simply act as ordinary anchor-tags. I want it to load the next page using AJAX, just like it does with the first page.
If you're inserting new content, that content would be dynamic, and the event handler can only be bound to elements that actually exist. You need to delegate the event to an element higher in the DOM that exists at the time you are attaching the event handler. I'll use the document, you'll use the closest non dynamic parent to delegate to :
$(document).on('click', '.ajax', function(event){
event.preventDefault();
$('#content').load("cnt/" + pattern.exec(this.href.substr(baseurl.length)) + ".php")
});
using $('a.ajax').live('click', stuff here)
will handle all links with class "ajax" whenever they happen to be added.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With