Skip to content Skip to sidebar Skip to footer

Best Way To Smooth Scrolling To An Internal Link

I've searched and see lots of examples about this subject but I couldn't best way for me. I'm just a bit familiar with JS and jQuery and I want to ask about smooth scrolling. &

Solution 1:

HTML:

<ul><li><ahref="#ppanjur"class="uruna">Plastik Panjur</a></li>
    [...]
</ul>

JS:

functionscrollToElement (selector) {
  $('html, body').animate({
    scrollTop: $(selector).offset().top
  }, 2000);    
};

$(document).on('click', 'a.uruna', function () {
  scrollToElement($(this).attr('href'));
});

or

functionscrollToElement (obj) {
  $('html, body').animate({
    scrollTop: obj.offset().top
  }, 2000);    
};

$(document).on('click', 'a.uruna', function () {
  scrollToElement($(this));
});

Solution 2:

I noticed that with JohnJohnGa's answer you get a "flicker" (at least for Google Chrome) where the page immediately pops to the anchor href position and back again before it scrolls there smoothly. This might not be noticeable with a fast computer, but it was definitely noticeable on the one I was working on. To get around this, I did the following:

$('a.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
    window.history.pushState(null, null, $($anchor.attr('href')).selector);
});

Note, this prevents the default event from firing and then uses window.history.pushState to mimic it. For old browsers that don't support pushState it will scroll to the correct location, but it just won't update the address location.

Solution 3:

Living demo: http://jsfiddle.net/wVEAy/2/

Note that for this case you would need to have an element with the same id as the one specified in the href tag of your link:

functionscrollToElement (selector) {
  $('html, body').animate({
    scrollTop: $(selector).offset().top
  }, 2000);    
};

$(document).on('click', 'a.uruna', function () {
    scrollToElement($(this).attr('href'));
});

Post a Comment for "Best Way To Smooth Scrolling To An Internal Link"