How to have a navigation full ajax?
I have a question.
I visited a site : http://currenthiphop.com/. And when I clicked on a link, the link on adress bar change to http://currenthiphop.com/#!/
+ link. (like Twitter, Faceboook...)
However, in the attribut href
, there is no #!
. Why ?
Is is a ajax navigation isn't ? How can I do something like t开发者_C百科his ?
Thanks
It is location.hash. Like in Facebook it is made with javascript. It is used to avoid use of GET and reload the page.
basic example - in the folder where are the php page and JavaScript you have some images (1.png, 2.png ... etc). Like Facebook (some time ago) if you copy the link and paste it, js checks if there is any hash and redirects you to the wanted image. The code is old, and it is not the best.
This oughta get you started.
http://jsfiddle.net/f6dBV/
EDIT - jsFiddle is actually not showing the location.hash bit. Here it is on my website: http://jfcoder.com/test/hash.html
<html>
<head>
<style type="text/css">
.content {
display: none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#menu a').each(function(){
id = $(this).attr('href');
id = id.substring(id.lastIndexOf('/'));
id = id.substring(0,id.indexOf('.'));
$(this).attr('rel',id);
});
$('#home').show();
$('#menu a').click(function(e){
e.preventDefault();
$('.content').hide();
$('#'+$(this).attr('rel')).show();
location.hash = '#!/'+$(this).attr('rel');
return false;
});
});
</script>
</head>
<body>
<div id="menu">
<a href="home.html">Home</a> -
<a href="one.html">One</a> -
<a href="two.html">Two</a> -
<a href="three.html">Three</a>
</div>
<div id="home" class="content">
Home content.
</div>
<div id="one" class="content">
One content.
</div>
<div id="two" class="content">
Two content.
</div>
<div id="three" class="content">
Three content.
</div>
</body>
</html>
Thanks to Jared Farrish.
I have one little extra addition that will allow you to get the active content after you refresh the page.
$(document).ready(function(){
$('#menu a').each(function(){
id = $(this).attr('href');
id = id.substring(id.lastIndexOf('/'));
id = id.substring(0,id.indexOf('.'));
$(this).attr('rel',id);
});
active_page = location.hash.substring(location.hash.lastIndexOf('/')+1)
if (active_page=='')
{
active_page='home'
}
$('#'+active_page).show();
$('#menu a').click(function(e){
e.preventDefault();
$('.content').hide();
$('#'+$(this).attr('rel')).show();
location.hash = '#!/'+$(this).attr('rel');
return false;
精彩评论