I’m using jQuery and ajax to load pages without reloading the entire website and I ran into a problem.
This is the jquery script:
$(function(){
$("a[rel='tab']").click(function(e){
e.preventDefault();
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
if(pageurl!=window.location){
$.ajax({url:pageurl+'?rel=tab',success: function(data){
$('#main-wrap').html(data);
}});
}
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab',success: function(data){
$('#main-wrap').html(data);
}});
});
and the html code is something like this:
<div class="nav"><a href="example1.html" rel="tab">Page 1</a></div>
<div class="ajax-content">
<div class="title"><a href="title_page.html" rel="tab">Title</a></div>
</div>
Now if I click “Page 1” that is outside the div where the ajax content is loaded it’s working but if I click “Title” that is inside the div, the whole page is reloaded(ajax not working).
It’s possible to make that “Title” link(which is inside the div where the ajax content is loaded) to work?
The actual problem is that you are adding the event handler to all
a[rel='tab']on document ready, but you are loading the target<a>after the fact. That means that they will not have the event handler bound to their click. You should use something likeliveor more importantlyon. The importance is event delegation, where you would use something like:This way, any
a[rel='tab']that is removed or added inside of the#containerelement has this event handler attached to it.