Reputation: 37
Im trying to animate the scroll to each section on button press. I have done lots of research and came across with this:
$('ul.nav').find('a').click(function () {
var $href = $(this).attr('href');
var $anchor = $('#' + $href).offset();
$('body').animate({scrollTop: $anchor.top});
return false;
});
But it's not working. It just scroll without the animation. Can somebody help me please?
My HTML code:
<nav id="nav">
<ul>
<li class="current"><a href="index.php">Hlavní stránka</a></li>
<li><a href="#rooms">Naše pokoje</a></li>
<li><a href="#prizes">Ceník</a></li>
<li><a href="#footer">Kontakt</a></li>
</ul>
</nav>
Upvotes: 0
Views: 35
Reputation: 33933
You just used a wrong selector...
Try with this:
$('#nav ul li a').click(function(e) {
// Get the href
var $href = $(this).attr('href');
// Animate only if the href contains the # character.
if($href.substr(0,1) == "#"){}
e.preventDefault();
// Here, the # sign is already present.
var $anchor = $($href).offset();
$('body').animate({scrollTop: $anchor.top},1000); // Set a delay here, in milliseconds.
}
});
And I would use preventDefault()
instead of return false;
EDITED to care about the first anchor which looks like to be a "real" link to trigger a page load.
Upvotes: 1
Reputation: 9380
You are looking for
$('#nav ul li a').click(function () {
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
Upvotes: 0