Gravatar of Jeroen Jeroen Pelgrims

jQuery scroll to element plugin

Posted on in javacript, jquery, software-development

This small plugin will scroll to a selected element when calling .scrollTo() on it. It has an optional parameter which specifies the duration of the scroll.

$.fn.scrollTo = function (duration) {
  if (duration == null) {
    duration = 1000;
  }

  var offset = $(this).offset().top - $(window).height() / 2 + $(this).height();
  $("html,body").animate(
    {
      scrollTop: offset,
    },
    duration
  );
};

For example, if i would have a div with the id "#mydiv" I would let the screen scroll to it using this code: $('#mydiv').scrollTo();

Or, if you want the animation to be slower $('#mydiv').scrollTo(2000);

The top of the selected element will be displayed at 50% of the screen unless the scrollbar is too short, then the element will be lower on the screen.

This post is written by Jeroen Pelgrims, an independent software developer who runs Digicraft.eu.

Hire Jeroen