I'm working on a one page scrolling site (with a sticky header) and want to add animated deep linking.
You can view the demo here:
http://www.creativecontroller.com/demo/onepage/
Here's what I'm trying to achieve:
- click on nav link, animate to div - in this case I'm using html5 sections (Done)
- have the hashtag displayed in the url like ...demo/onepage/#about
- if the user clicks another link, it animates, updates the url hashtag and animates to the right div
- if the user clicks the back button it animates back to the previous div instead of just snapping to it
- try to do this without using any plugins (just jQuery)
Here's the jQuery I'm using for the page scrolling and sticky header:
// Page scrolling
$(function() {
$('a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 60
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});
// Sticky Nav
$(window).scroll(function(e) {
var nav_anchor = $(".nav_anchor").offset().top;
if ($(this).scrollTop() >= nav_anchor && $('.nav').css('position') != 'fixed')
{
$('.nav').css({
'position': 'fixed',
'top': '0px'
});
$('.nav_anchor').css('height', '60px');
}
else if ($(this).scrollTop() < nav_anchor && $('.nav').css('position') != 'relative')
{
$('.nav_anchor').css('height', '0px');
$('.nav').css({
'position': 'relative'
});
}
});
Any help would be appreciated, thanks!
UPDATE:
I found a site that does what I've described above:
http://www.maddim.com/demos/spark-r6/
First, change your anchor tags from absolute to relative URL's (href="#about"
rather than href="http://blahfdsjkld.com#about"
). Then update your function like so:
// Page scrolling
$(function() {
$('a').bind('click',function(event){
// Do this first
event.preventDefault();
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 60
}, 1500,'easeInOutExpo');
// Use an id that isn't on the page, hence the capitalization of the first letter
window.location.hash = $anchor.html().charAt(0).toUpperCase() + $anchor.html().slice(1);
});
});