Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to an element using jQuery

I need the page to scroll just so that an element is visible.

Options I've tried:

  • jQuery's scrollTo: the problem is that the page scrolls so that the element is on top (or at least it tries to do that, much like how this works: <a name="xyz"> / <a href="#xyz">). I want the minimum amount of scrolling, so that the entire element is visible (and, if the element is too tall, work like the anchor there).

  • scrollIntoView: awful. I want it to scroll smoothly (like $.scrollTo($('#id1'), 'fast');). Also, it doesn't seem to do what I want either.

like image 803
cambraca Avatar asked Nov 18 '10 17:11

cambraca


2 Answers

What you need to do is identify the position within the page of the element, top and bottom (and left/right if you are considering horizontal scrolling). Then identify the current position of the viewport on the window, the scrollTop of the window should then be animated to whatever value will bring the other just in to view.

I just knocked up the following in this editor, so it's untested, but will give you the general idea for a plugin.

Updated - to show version that worked for the OP, as well as a smoother version

jQuery.fn.scrollMinimal = function(smooth) {
  var cTop = this.offset().top;
  var cHeight = this.outerHeight(true);
  var windowTop = $(window).scrollTop();
  var visibleHeight = $(window).height();

  if (cTop < windowTop) {
    if (smooth) {
      $('body').animate({'scrollTop': cTop}, 'slow', 'swing');
    } else {
      $(window).scrollTop(cTop);
    }
  } else if (cTop + cHeight > windowTop + visibleHeight) {
    if (smooth) {
      $('body').animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing');
    } else {
      $(window).scrollTop(cTop - visibleHeight + cHeight);
    }
  }
};

$('#item').scrollMinimal();
like image 116
Orbling Avatar answered Sep 20 '22 17:09

Orbling


There's a plugin for just what you need

I don't want to copy the code from blog post, because it can get outdated (due to upgrades). But anyway. You can find all details and code about the .scrollintoview() jQuery plugin on blog post.

Usage

Contrary to scrollTo() plugin where you have to provide scrollable element this plugin only requires you to provide the element you'd like to scroll into view. Plugin finds nearest scrollable ancestor (with scrollbars) and scrolls to the element with animation, so user doesn't loose track of their position in the page.

The good thing is also that it won't scroll anything if element is already within visible boundaries of scrollable ancestor.

 $("ElementSelector").scrollintoview();

That's it most of the time. But if you need to set some additional settings, there are some you can change and provide custom behaviour:

scrollintoview: function (options) {
    /// <summary>Scrolls the first element in the set into view by scrolling its closest scrollable parent.</summary>
    /// <param name="options" type="Object">Additional options that can configure scrolling:
    ///        duration (default: "fast") - jQuery animation speed (can be a duration string or number of milliseconds)
    ///        direction (default: "both") - select possible scrollings ("vertical" or "y", "horizontal" or "x", "both")
    ///        complete (default: none) - a function to call when scrolling completes (called in context of the DOM element being scrolled)
    /// </param>
    /// <return type="jQuery">Returns the same jQuery set that this function was run  on.</return>
like image 40
Robert Koritnik Avatar answered Sep 21 '22 17:09

Robert Koritnik