This has been driving me nuts! I've searched and tried a bunch of suggestions that seem like they should work, so I must be doing something foolish.
$(document).ready(function(){
$('.trigger').click(function(){
var link = $(this).attr("href");
$('#target').load(link);
return false;
});
});
and
<div id='content'>
This is some stuff that I want left alone.
<a href="testload1.html" class="trigger">Click here</a>
<a href="testload2.html" class="trigger">Click here</a>
</div>
<div id="target">
</div>
I'm trying to load the html document "testload1" and "testload2" (which just contain a line of text) into the "target" div.
Instead what happens is the "testload1" page just loads as a normal link would.
edit: more info
I tried the suggested changes below with no difference. This leads me to think there is something wrong with the rest of the file, so here it is:
<!DOCTYPE html>
<head>
<title>test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.trigger').click(function(){
var link = $(this).attr("href");
$('#target').load(link);
return false;
});
});
</script>
</head>
<body>
<div id='content'>
This is some stuff that I want left alone.
<a href="testload1.html" class="trigger">Click here</a>
<a href="testload2.html" class="trigger">Click here</a>
</div>
<div id="target">
</div>
</body>
</html>
Is there any reason this shouldn't work?
Maybe you just need to prevent the default action when you click a link or check the url.
Try this:
$(document).ready(function(){
$('.trigger').click(function(e){
e.preventDefault();
var link = $(this).attr("href");
$('#target').load(link);
});
});
Maybe your links are created dynamically, use event delegation with .on()
:
$(document).ready(function(){
$('body').on('click', '.trigger', function () {
var link = $(this).attr("href");
$('#target').load(link);
return false;
});
});
References:
.on()
- jQuery API DocumentationThis is the correct code:
$(document).ready( function(){
$('.trigger').click(function(){
var link = $(this).attr("href");
$('#target').load( link + ' body' );
return false;
});
});
and it's better to have a basic html structure in target files like this:
<html>
<body>
Content
</body>
</html>