JQuery smooth scroll to div using animation

Overview: I am using anchor labels to scroll to their respective divs assigned in the 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 an anchor tag, the window scrolls to a specific div, but the scroll is not smooth or slow. I would rather say that this is not scrolling at all. It just jumps to that div.

I used animation and also used the slow parameter with it. So what is my mistake? How can I get the sleek scroll I'm looking for here.

Web site:

http://irankmedia.com/uskincare/

Hi please check the navigation bar on this website which does not give me the smooth scrolling effect I am expecting.

Hope this gives a clear idea.

+3


source to share


3 answers


The task $('#'+ $href).offset();

, since it href

has #

it itself , it throws an error, for exampleUncaught 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

+3


source


Just remove the '#' used with $ href , otherwise your code will work 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 is throwing syntax error, unrecognized expression: ## howToUse

+2


source


Try the following:

$('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

+2


source







All Articles