I was attempting to follow the example used here: http://html5.gingerhost.com/ Instead of using JSON, I decided to use jQuery's .load() instead,
Here's my code:
$(function() {
$('a').click(function(e) {
$('img#logo').stop().hide().fadeIn( "slow" );
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$('#load').load( url + " #load2").stop().hide().fadeIn( 'slow' );
}
The example's loadContent function:
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
HTML:
<head>
<meta charset="utf-8">
<title>Andy Simon</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="javascript.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Raleway:100' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="main">
<div id="top">
<div id="logo">
<div>
<a id="logo" href="index.html"><img id="logo" src="logo1.png" /></a><span id="logo_text">simon</span>
</div>
</div>
<div id="nav">
<a class="nav_link" id="work" href="work.html"> work . </a>
<a class="nav_link" id="work" href="work.html"> about . </a>
<a class="nav_link" id="work" href="contact.html"> contact </a>
</div>
</div>
<div id ="middle">
<div id="load">
<div id="load2">
home home andy pandy home home home
</div>
</div>
</div>
<div id="foot">
</div>
</div>
</body>
When I click on a link, the page reloads, which is what I'm trying to prevent. I thought my e.preventDefault() would stop that. Any help is appreciated!
You can put a 'return false;' at your js code to prevent it to upload:
$('a').click(function(e) {
e.preventDefault();
$('img#logo').stop().hide().fadeIn( "slow" );
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
return false;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.