Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a jQuery event handler for AJAX-loaded data [duplicate]

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.

like image 885
Steen Schütt Avatar asked Dec 11 '12 14:12

Steen Schütt


2 Answers

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")
});
like image 135
adeneo Avatar answered Nov 16 '22 09:11

adeneo


using $('a.ajax').live('click', stuff here) will handle all links with class "ajax" whenever they happen to be added.

like image 1
Randy Hall Avatar answered Nov 16 '22 09:11

Randy Hall