Search code examples
javascriptjqueryscrollanchorsmoothing

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.

    <a name="urunler"></a>
<ul>
    <li><a href="#ppanjur" class="uruna">Plastik Panjur</a></li>
    <li><a href="#ipanjur" class="uruna">Alüminyum (İthal / Yalıtımlı) Panjur</a></li>
    <li><a href="#opanjur" class="uruna">Otomatik Panjur</a></li>
    </ul>

I've a navigation like this. This scrolls instatly. But I want to do it slowly. Which is the shortest & easiest way for this? I'm more familiar to JS and I don't want to download and use JS plugins.

  1. I need to know full syntax with a click method for my links (they all have same class)
  2. Should I remove href park from links?

Waiting for your help & still searching

EDIT!!!: In this situation, I need only one class. Is it possible to give this property for multiple classes?

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

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

I've got ('click', 'a.uruna', function (), how can I insert another class here or should I just write:

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

Solution

  • HTML:

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

    JS:

    function scrollToElement (selector) {
      $('html, body').animate({
        scrollTop: $(selector).offset().top
      }, 2000);    
    };
    
    $(document).on('click', 'a.uruna', function () {
      scrollToElement($(this).attr('href'));
    });
    

    or

    function scrollToElement (obj) {
      $('html, body').animate({
        scrollTop: obj.offset().top
      }, 2000);    
    };
    
    $(document).on('click', 'a.uruna', function () {
      scrollToElement($(this));
    });