Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Created February 6, 2018 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagdeepsingh/57b780a7cfbe8a25826a7c04754d8023 to your computer and use it in GitHub Desktop.
Save jagdeepsingh/57b780a7cfbe8a25826a7c04754d8023 to your computer and use it in GitHub Desktop.
jQuery - Go to an element on page

Go to an element on page using jQuery.

// @params
//   ms - milliseconds
//   top - padding from top after scrolling to the element
(function(jQuery) {
  jQuery.fn.goTo = function(ms, top) {
    if (top == null) {
      top = 10;
    }
    $('html, body').animate({
      scrollTop: $(this).offset().top - top + 'px'
    }, ms);
    return this;
  };
})(jQuery);

Usage

$(selector).goTo(500);
$(selector).goTo(500, 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment