Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery smooth scroll to a div using animate

Tags:

jquery

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.

like image 860
Kiran Dash Avatar asked Jul 21 '15 07:07

Kiran Dash


2 Answers

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

like image 167
Arun P Johny Avatar answered Oct 02 '22 23:10

Arun P Johny


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

like image 34
Ash Avatar answered Oct 02 '22 23:10

Ash