Kiran Dash
Kiran Dash

Reputation: 4956

jQuery smooth scroll to a div using animate

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.

Upvotes: 6

Views: 11908

Answers (3)

Himesh Aadeshara
Himesh Aadeshara

Reputation: 2121

Just remove the '#' used with $href otherwise your code is working fine dude

$('ul.nav').find('a').click(function(){
    var $href = $(this).attr('href');
    var $anchor = $($href).offset();
    $('body').animate({ 
          scrollTop: $anchor.top 
    },'slow');
    return false;
});

it's throwing Syntax error, unrecognized expression: ##howToUse

Upvotes: 3

Ash
Ash

Reputation: 2108

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

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 3

Related Questions