Lewis Tyler Lewis Tyler - 4 months ago 14
Ajax Question

Load page contents and links inside of div;

Okay basically what I'm trying to achieve is load links that are clicked inside of the

targetDiv
inside the div not load on the whole page; Below is the script I'm currently using.

<div id = "targetDiv"></div>

<script>
$('document').ready(function() {
$('#targetDiv').load('/test.php');
});
</script>


So the problem I'm having is that when a link is clicked which is loaded in the
targetDiv
the whole page loads and the user is taken from the original page and taken to the new page; and what I want to happen is the new page load within the
targetDiv
.

Answer

You need to have a click handler that prevents the default event and also uses the href to load() again

$(function(){
    $('#targetDiv').on('click', 'a', function(e){
         e.preventDefault();// prevent browser from opening url
         $('#targetDiv').load(this.href);    
    });
});

This is a delegated listener to account for future <a> that don't exist at run time

Comments