Overview: I am using anchor tags to scroll to their respective divs as assigned in href.
HTML Markup:
<ul class="nav navbar-nav">
<li><a href="#howToUse">How to use</a></li>
<li><a href="#benefits">Benefits</a></li>
</ul>
<div id="howToUse">
Some content
</div>
<div id="benefits">
Some content
</div>
jQuery:
$('ul.nav').find('a').click(function(){
var $href = $(this).attr('href');
var $anchor = $('#'+$href).offset();
$('body').animate({ scrollTop: $anchor.top },'slow');
return false;
});
Problem: So, now when I click on the anchor tag the window scrolls to the particular div but the scroll is not smooth or slow. I would rather say it is not scrolling at all. It just jumps to that div.
I have used animate and also used the parameter slow with it. So, what is my mistake here? How can I achieve the smooth scroll that I am lookin for here.
Website:
http://irankmedia.com/uskincare/
Hi there please check the navigation bar in this website which doesn't give me the smooth scroll effect I am expecting.
Hope it will bring a clear idea.
The problem is $('#'+ $href).offset();
, since the href
itself has #
, it throws an error like Uncaught Error: Syntax error, unrecognized expression: ##howToUse
$('ul.nav').find('a').click(function (e) {
e.preventDefault();
var target = $(this).attr('href');
var $anchor = $(target).offset();
$('body').stop().animate({
scrollTop: $anchor.top
}, 'slow');
});
Demo: Fiddle
Try this:
$('ul.nav').find('a').click(function() {
var $href = $(this).attr('href');
//var $anchor = $('#'+$href).offset();
$('html, body').animate({
scrollTop: $($href).offset().top
}, 2000);
return false;
});
Demo here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With