Search code examples
javascriptjqueryscrolladdclasssmoothing

how to add class smoothscroll to a link defined in jquery


I have a down button div that I want to have the smoothScroll class added to so that when it is clicked, the smooth scrolling happens before it jumps to the link that is attached to it in the JS file. I'm just not sure how to make the addClass run before the window.location everytime I try it it breaks.

HTML:

<div id="downButton">
    <i class="fa fa-angle-down"></i>
  </div>

JS:

  $(function() {
  // This will select everything with the class smoothScroll
  // This should prevent problems with carousel, scrollspy, etc...
    $('.smoothScroll').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000); // The number here represents the speed of the scroll in milliseconds
          return false;
        }
      }
    });
  });
  });

 $('#downButton').click(function () {
    window.location = '#aboutSection';
 }); 

Solution

  • The easiest way to make this quickly work would be like this:

    $(function(){
        $('#downButton').click(function () {
            var target = $('#aboutSection');
            $('html,body').animate({
                    scrollTop: target.offset().top
                  }, 1000);
         }); 
    });
    

    if you'd like to make it more re-usable I'd do it this way:

    HTML:

    <div id="downButton" class="scrollme" data-goto="#aboutSection">
        <i class="fa fa-angle-down"></i>
    </div>
    

    Then the javascript would be:

    $(function() {
      $('.scrollme').click(function(){
          scrollme(this);
      });
    });
    
    function scrollme(el){
        var id = $(el).data('target');
        var $target = $('#' + id);
        console.log($target.length)
        $('html,body').animate({
            scrollTop: $target.offset().top
        }, 1000);
    }
    

    Then you just have to add a class of scrollme to any element with a data-target attribute with the id of the element to which to scroll.