I am trying to ‘ajaxify’ standard links. I am using the jQuery on() function to intercept the click and retrieve the content dynamically:
$('.nextLink').on("click", function(e) {
url = $(this).attr( 'href' ).replace( /^#/, '' );
$.get(url, null, function(response) {
$('#searchResults').replaceWith(response);
});
});
This works fine except that the standard link behavior still occurs so I get the content using ajax but then it’s wiped by a full page refresh. I tried returning false from the handler to prevent the normal submit
$('.nextLink').on("click", function(e) {
...
return false;
}
This works however I also have links in the content which is loaded by ajax. My understanding is that jQuery’s on() function should rebind the handlers for content loaded using ajax however it seems adding return false prevents this happening.
So it seems i am in a catch-22 situation, I can either allow the event bubbling to occur which allows ‘on()’ to work correctly however I also get a non-ajax submit, or I can prevent the standard submit but this breaks on()
Can someone tell me the best way to handle this situation?
Many thanks
Use
preventDefault()to stop the default actionto also bind the handler on new added elements you need to use event delegation to capture the click event on a parent element of
.nextLink, e.g. withSee on() usage on jQuery docs