By DiegoP.


2011-07-13 09:49:44 8 Comments

I have this input element:

<input type="text" class="textfield" value="" id="subject" name="subject">

Then I have some other elements, like other text inputs, textareas, etc.

When the user clicks on that input with #subject, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.

The last item of the page is a submit button with #submit:

<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">

The animation should not be too fast and should be fluid.

I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.

25 comments

@cynya 2018-09-22 04:25:31

This is Atharva's answer from: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView. Just wanted to add if your document is in an iframe, you can choose an element in the parent frame to scroll into view:

 $('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();

@Steve 2011-07-13 09:52:36

Assuming you have a button with the id button, try this example:

$("#button").click(function() {
    $([document.documentElement, document.body]).animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function (){
            $("#click").click(function (){
                $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 2000);
            });
        });
    </script>
    <div id="div1" style="height: 1000px; width 100px">
        Test
    </div>
    <br/>
    <div id="div2" style="height: 1000px; width 100px">
        Test 2
    </div>
    <button id="click">Click me</button>
</html>

@Jānis Elmeris 2012-04-25 14:43:07

This will not work in all cases. See stackoverflow.com/questions/2905867/…

@Barry Chapman 2013-04-11 02:39:09

you should not really animate this to multiple elements (html and body)

@s3m3n 2013-05-10 00:01:01

@BarryChapman not exactly. After googling I've found this, so both tags are needed if you don't want to have extra logic per browser type.

@AfromanJ 2013-07-16 15:01:25

This function made my page bounce before executing. To stop this use 'e.preventDefault();' on your function '...click(function (e){...'.

@jon 2013-08-05 11:23:03

This doesn't seem to work on all IOS devices, on some devices it stops the click event from working until user scrolls manually. don't know why, would really like ot know why.

@Pascal 2013-09-06 09:20:18

My element 'elementtoScrollToID' has for the offset no top value how else can I scroll to it then?

@Rory O'Kane 2013-09-20 19:53:46

If you don't want animation, and instead want to jump instantly to the element, use .scrollTop(…) instead of .animate({scrollTop: …}, …).

@Francisco Corrales Morales 2014-01-20 23:26:07

@RoryO'Kane can you provide a JSFiddle that works without animation ?

@Rory O'Kane 2014-01-21 17:39:38

@FranciscoCorrales A jsFiddle without animation. In the click handler function, write $('html, body').scrollTop( $("#div2").offset().top ), which uses .offset().

@Sander 2014-01-23 08:09:11

In addition to you're solution (which works great), you can add an on complete function that adds the hashtag to the url. In this case it won't scroll, because the scrollTo already scrolled to the right position, and if a user copies the URL it will automatically snap to the right place on the page.

@yujohnnyzhou 2014-03-18 05:12:04

Just a little improvement. I think it is better to cache the Element $(html, body) by var root = $(html, body)

@Guido Celada 2014-08-28 18:11:53

Thanks! in my case i had a navbar adding an offset, so if you have this case, do like me and substract the height of the navbar (in my case: 80px) : scrollTop: $("#elementtoScrollToID").offset().top - 80

@Ben 2014-10-04 15:20:23

Much much better that javascripts' scrollTo or scrollBy methods. Thank you very much.

@carterh062 2015-01-22 05:03:58

For anyone who has trouble with the flash that might come after the click with this scroll sample, you can call e.preventDefault(); I got this from here: stackoverflow.com/questions/10614446/…

@henry 2015-01-29 13:57:31

@Janis what were you referring to? I read through the question you linked and don't see any discussion of failure

@Jānis Elmeris 2015-02-02 13:05:27

@henry I was probably referring to offset().top not being exactly the needed value to scroll to in all cases. See claviska's comment there, after which the accepted answer apparently has been modify to take into account the scrollbar of the container.

@BoatCode 2015-03-20 16:17:58

if you use a callback to run when the animation is complete and notice the callback fires twice with this solution, try using "$('html body').animate(..." instead of "$('html, body').animate(..." the comma created two animate events. one for html, one for body. you really just want one for the html body Thanks @T.J. Crowder stackoverflow.com/questions/8790752/…

@Bradley Flood 2015-12-13 23:53:56

Could you explain why both html and body are selected? Wouldn't this result in two animations being run in parallel? One for each selected element?

@R. Canser Yanbakan 2016-02-10 12:26:03

Actually, this code works for two times if you set a callback function in animate. Look here: jsfiddle.net/dxj1d3x8 To prevent this, use one element only

@weaveoftheride 2016-03-15 11:28:13

If you are using material design lite then this method has some problems

@Herman Nz 2016-07-04 20:13:04

I added 'return false' to avoid from opening new browser's tab.

@Erick Jimenez 2016-10-17 13:33:37

You need to add the event param in the function handler and call the preventDefault function from event to avoid unexpected functionality @Steve

@Mile Mijatovic 2017-01-01 11:13:59

Unfortunately, this solution does not work on mobile (android and ios)... Do you have idea why?

@adamj 2017-02-28 23:49:04

@Steve This is great, but will fire twice, which means if you have other code running in the complete function of animate() it will do it twice. I highly recommend just doing a browser check and running the animate on the correct element.

@Warface 2013-09-05 11:53:54

Using this simple script

if($(window.location.hash).length > 0){
        $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}

Would make in sort that if a hash tag is found in the url, the scrollTo animate to the ID. If not hash tag found, then ignore the script.

@DevWL 2016-01-11 04:32:11

Very simple and easy to use custom jQuery plugin. Just add the attribute scroll= to your clickable element and set its value to the selector you want to scroll to.

Like so: <a scroll="#product">Click me</a>. It can be used on any element.

(function($){
    $.fn.animateScroll = function(){
        console.log($('[scroll]'));
        $('[scroll]').click(function(){
            selector = $($(this).attr('scroll'));
            console.log(selector);
            console.log(selector.offset().top);
            $('html body').animate(
                {scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
                1000
            );
        });
    }
})(jQuery);

// RUN
jQuery(document).ready(function($) {
    $().animateScroll();
});

// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>

@Irshad Khan 2017-10-10 13:03:06

Easy way to achieve the scroll of page to target div id

var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);

@FAjir 2017-09-23 00:11:45

If you want to scroll within an overflow container (instead of $('html, body') answered above), working also with absolute positioning, this is the way to do :

var elem = $('#myElement'),
    container = $('#myScrollableContainer'),
    pos = elem.position().top + container.scrollTop() - container.position().top;

container.animate({
  scrollTop: pos
}

@Asad Ali 2018-03-22 05:56:37

Nice way to go.

@sanket patel 2018-07-11 13:17:16

this worked for me. thanks.

@FAjir 2018-07-13 15:11:46

so why no upvote ? :)

@Rezgar Cadro 2014-08-29 11:19:31

A compact version of "animate" solution.

$.fn.scrollTo = function (speed) {
    if (typeof(speed) === 'undefined')
        speed = 1000;

    $('html, body').animate({
        scrollTop: parseInt($(this).offset().top)
    }, speed);
};

Basic usage: $('#your_element').scrollTo();

@Timothy Perez 2012-10-05 08:50:48

jQuery .scrollTo() Method

jQuery .scrollTo(): View - Demo, API, Source

I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?


Examples Usage:

$('body').scrollTo('#target'); // Scroll screen to target element

$('body').scrollTo(500); // Scroll screen 500 pixels down

$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down

Options:

scrollTarget: A element, string, or number which indicates desired scroll position.

offsetTop: A number that defines additional spacing above scroll target.

duration: A string or number determining how long the animation will run.

easing: A string indicating which easing function to use for the transition.

complete: A function to call once the animation is complete.

@alex 2013-02-02 22:15:43

The demo does not work on chrome

@Timothy Perez 2013-02-05 13:56:35

It was working until a recent update on chrome. I have a version that works that I'm currently using on memoryboxweddings.com/photography-posts (if you want to try it out). I'll post an update once it's fixed.

@Timothy Perez 2013-02-14 19:45:04

Fixed, turns out it was actually a JS file from jquery.com that was killing it. Should work now if you try it.

@ravishi 2013-03-22 01:07:01

I'm using this plugin and it works great. Thanks! Does the plugin have a license associated with it?

@Robert Massaioli 2013-03-24 05:30:02

@TimothyPerez: I am sure that means something permissive for commercial use? I am sure that there are many people that would like to just use that snippet of code anywhere in their websites and that would help them sleep that little bit easier at night? Maybe something like the MIT license might suit your needs? en.wikipedia.org/wiki/MIT_License

@kiranvj 2013-07-05 16:08:19

$('body') didn't work in FF, so tried $('html, body') which worked.

@Arturs 2013-11-07 15:18:34

If anyone need's this script source, then here you can get it flesler.com/jquery/scrollTo/js/jquery.scrollTo-min.js

@Jonathan 2014-01-31 17:36:05

hi, the source that Arthur posted is ok, the only difference is that there isn't a offsetTop option, the correct is only offset.

@Matias 2015-06-10 14:13:27

I've tested the code from the webpage but didn´t work. I had to download it from here github.com/flesler/jquery.scrollTo/blob/master/…

@karlcow 2016-08-05 02:14:52

@TimothyPerez It seems there is an issue with your code, we (Mozilla) would love to see solved. That would be cool if you could help. github.com/webcompat/web-bugs/issues/1574

@Alex Rindone 2017-04-26 22:29:00

This doesn't work in chrome. I did the suggestion in the comments, downvoting.

@Alex78191 2017-05-17 09:20:26

@AlexRindone This demo works in Chrome demos.flesler.com/jquery/scrollTo Site with old demo isn't working now.

@user7601056 2017-02-27 10:09:12

Animations:

// slide to top of the page
$('.up').click(function () {
    $("html, body").animate({
        scrollTop: 0
    }, 600);
    return false;
});

// slide page to anchor
$('.menutop b').click(function(){
    //event.preventDefault();
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 600);
    return false;
});

// Scroll to class, div
$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#target-element").offset().top
    }, 1000);
});

// div background animate
$(window).scroll(function () {

    var x = $(this).scrollTop();

    // freezze div background
    $('.banner0').css('background-position', '0px ' + x +'px');

    // from left to right
    $('.banner0').css('background-position', x+'px ' +'0px');

    // from right to left
    $('.banner0').css('background-position', -x+'px ' +'0px');

    // from bottom to top
    $('#skills').css('background-position', '0px ' + -x + 'px');

    // move background from top to bottom
    $('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');

    // Show hide mtop menu  
    if ( x > 100 ) {
    $( ".menu" ).addClass( 'menushow' );
    $( ".menu" ).fadeIn("slow");
    $( ".menu" ).animate({opacity: 0.75}, 500);
    } else {
    $( ".menu" ).removeClass( 'menushow' );
    $( ".menu" ).animate({opacity: 1}, 500);
    }

});

// progres bar animation simple
$('.bar1').each(function(i) {
  var width = $(this).data('width');  
  $(this).animate({'width' : width + '%' }, 900, function(){
    // Animation complete
  });  
});

@Shahdat 2017-01-04 15:11:49

$('html, body').animate(...) does not for me on iphone, android chrome safari browser.

I had to target root content element of the page.

$('#cotnent').animate(...)

Here is what I have ended up with

if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {           
    $('#content').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
   }, 'slow');
}
else{
    $('html, body').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
    }, 'slow');
}

All body content wired up with a #content div

<html>
....
<body>
<div id="content">
....
</div>
</body>
</html>

@Alex Podworny 2017-02-10 21:22:40

You really shouldn't use user agent sniffing. webaim.org/blog/user-agent-string-history

@steven iseki 2016-11-23 12:33:07

I set up a module scroll-element npm install scroll-element. It works like this:

import { scrollToElement, scrollWindowToElement } from 'scroll-element'

/* scroll the window to your target element, duration and offset optional */
let targetElement = document.getElementById('my-item')
scrollWindowToElement(targetElement)

/* scroll the overflow container element to your target element, duration and offset optional */
let containerElement = document.getElementById('my-container')
let targetElement = document.getElementById('my-item')
scrollToElement(containerElement, targetElement)

Written with help from the following SO posts:

Here is the code:

export const scrollToElement = function(containerElement, targetElement, duration, offset) {
  if (duration == null) { duration = 1000 }
  if (offset == null) { offset = 0 }

  let targetOffsetTop = getElementOffset(targetElement).top
  let containerOffsetTop = getElementOffset(containerElement).top
  let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
  scrollTarget += offset
  scroll(containerElement, scrollTarget, duration)
}

export const scrollWindowToElement = function(targetElement, duration, offset) {
  if (duration == null) { duration = 1000 }
  if (offset == null) { offset = 0 }

  let scrollTarget = getElementOffset(targetElement).top
  scrollTarget += offset
  scrollWindow(scrollTarget, duration)
}

function scroll(containerElement, scrollTarget, duration) {
  let scrollStep = scrollTarget / (duration / 15)
  let interval = setInterval(() => {
    if ( containerElement.scrollTop < scrollTarget ) {
      containerElement.scrollTop += scrollStep
    } else {
      clearInterval(interval)
    }
  },15)
}

function scrollWindow(scrollTarget, duration) {
  let scrollStep = scrollTarget / (duration / 15)
  let interval = setInterval(() => {
    if ( window.scrollY < scrollTarget ) {
      window.scrollBy( 0, scrollStep )
    } else {
      clearInterval(interval)
    }
  },15)
}

function getElementOffset(element) {
  let de = document.documentElement
  let box = element.getBoundingClientRect()
  let top = box.top + window.pageYOffset - de.clientTop
  let left = box.left + window.pageXOffset - de.clientLeft
  return { top: top, left: left }
}

@Jonathan 2016-08-02 23:09:14

With this solution you do not need any plugin and there's no setup required besides placing the script before your closing </body> tag.

$("a[href^='#']").on("click", function(e) {
  e.preventDefault();
  $("html, body").animate({
    scrollTop: $($(this).attr("href")).offset().top
  }, 1000);
});

if ($(window.location.hash).length > 1) {
  $("html, body").animate({
    scrollTop: $(window.location.hash).offset().top
  }, 1000);
}

On load, if there is a hash in the address, we scroll to it.

And - whenever you click an a link with an href hash e.g. #top, we scroll to it.

@Tallboy 2016-08-18 14:57:58

This should probably be > 1 instead of 0, just because /# causes this script to break

@Jonathan 2016-08-22 23:28:01

You shouldn't technically end up with an empty hash URL unless the links are poorly constructed but TY. (although my own version of this code has this patch included already ^^)

@roncli 2016-10-20 16:46:15

There is a jitter associated with this code, however it's easily fixable. You need to return false; at the end of the on click event to prevent the default action - immediately scrolling to the anchor - from happening.

@Jonathan 2016-10-20 17:37:37

@roncli good point - alternatively you can just do e.preventDefault();

@davidcondrey 2014-07-18 18:06:05

jQuery(document).ready(function($) {
  $('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash,
        $target = $(target);

    $('html, body').stop().animate( {
      'scrollTop': $target.offset().top-40
    }, 900, 'swing', function () {
      window.location.hash = target;
    } );
  } );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul role="tablist">
  <li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>
  <li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
  <li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
</ul>

<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>

@bubencode 2018-08-12 14:27:51

To make it more universal and to remove unnecessary placing of hashtag into browser link window I just tweaked the code as below: jQuery(document).ready(function($) { $(document).on( "click", 'a[href^="#"]', function( e ) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ scrollTop: $target.offset().top - 100}, 1000); }); });

@martinh_kentico 2016-02-26 11:40:12

For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling. In our case we don't scroll the full body, but just particular elements with overflow: auto; within a larger layout.

It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.

var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');

$scrollTo.prepend(inputElem);
inputElem.css({
  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();

@Khaled.K 2015-11-28 12:34:55

When the user clicks on that input with #subject, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.

The last item of the page is a submit button with #submit

$('#subject').click(function()
{
    $('#submit').focus();
    $('#subject').focus();
});

This will first scroll down to #submit then restore the cursor back to the input that was clicked, which mimics a scroll down, and works on most browsers. It also doesn't require jQuery as it can be written in pure JavaScript.

Can this fashion of using focus function mimic animation in a better way, through chaining focus calls. I haven't tested this theory, but it would look something like this:

<style>
  #F > *
  {
    width: 100%;
  }
</style>

<form id="F" >
  <div id="child_1"> .. </div>
  <div id="child_2"> .. </div>
  ..
  <div id="child_K"> .. </div>
</form>

<script>
  $('#child_N').click(function()
  {
    $('#child_N').focus();
    $('#child_N+1').focus();
    ..
    $('#child_K').focus();

    $('#child_N').focus();
  });
</script>

@isapir 2015-11-18 19:46:13

I wrote a general purpose function that scrolls to either a jQuery object, a CSS selector, or a numeric value.

Example usage:

// scroll to "#target-element":
$.scrollTo("#target-element");

// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);

// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");

The function's code:

/**
* Scrolls the container to the target position minus the offset
*
* @param target    - the destination to scroll to, can be a jQuery object
*                    jQuery selector, or numeric position
* @param offset    - the offset in pixels from the target position, e.g.
*                    pass -80 to scroll to 80 pixels above the target
* @param speed     - the scroll speed in milliseconds, or one of the
*                    strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
*                    be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {

    if (isNaN(target)) {

        if (!(target instanceof jQuery))
            target = $(target);

        target = parseInt(target.offset().top);
    }

    container = container || "html, body";
    if (!(container instanceof jQuery))
        container = $(container);

    speed = speed || 500;
    offset = offset || 0;

    container.animate({
        scrollTop: target + offset
    }, speed);
};

@Tejasvi Hegde 2014-02-06 15:39:09

The solution by Steve and Peter works very well.

But in some cases, you may have to convert the value to an integer. Strangely, the returned value from $("...").offset().top is sometimes in float.
Use: parseInt($("....").offset().top)

For example:

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: parseInt($("#elementtoScrollToID").offset().top)
    }, 2000);
});

@hashchange 2015-08-17 09:18:15

In most cases, it would be best to use a plugin. Seriously. I'm going to tout mine here. Of course there are others, too. But please check if they really avoid the pitfalls for which you'd want a plugin in the first place - not all of them do.

I have written about the reasons for using a plugin elsewhere. In a nutshell, the one liner underpinning most answers here

$('html, body').animate( { scrollTop: $target.offset().top }, duration );

is bad UX.

  • The animation doesn't respond to user actions. It carries on even if the user clicks, taps, or tries to scroll.

  • If the starting point of the animation is close to the target element, the animation is painfully slow.

  • If the target element is placed near the bottom of the page, it can't be scrolled to the top of the window. The scroll animation stops abruptly then, in mid motion.

To handle these issues (and a bunch of others), you can use a plugin of mine, jQuery.scrollable. The call then becomes

$( window ).scrollTo( targetPosition );

and that's it. Of course, there are more options.

With regard to the target position, $target.offset().top does the job in most cases. But please be aware that the returned value doesn't take a border on the html element into account (see this demo). If you need the target position to be accurate under any circumstances, it is better to use

targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;

That works even if a border on the html element is set.

@kayz1 2015-07-03 06:27:36

var scrollTo = function($parent, $element) {
    var topDiff = $element.position().top - $parent.position().top;

    $parent.animate({
        scrollTop : topDiff
    }, 100);
};

@vascogaspar 2015-06-21 16:46:37

This is my approach abstracting the ID's and href's, using a generic class selector

$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 500);
  });
});
<!-- example of a fixed nav menu -->
<ul class="nav">
  <li>
    <a href="#section-1" class="nav-item js-scroll-to">Item 1</a>
  </li>
  <li>
    <a href="#section-2" class="nav-item js-scroll-to">Item 2</a>
  </li>
  <li>
    <a href="#section-3" class="nav-item js-scroll-to">Item 3</a>
  </li>
</ul>

@Benjamin Oakes 2015-01-28 17:00:19

If you are only handling scrolling to an input element, you can use focus(). For example, if you wanted to scroll to the first visible input:

$(':input:visible').first().focus();

Or the first visible input in an container with class .error:

$('.error :input:visible').first().focus();

Thanks to Tricia Ball for pointing this out!

@Roman Shamritskiy 2014-03-25 00:10:13

To show the full element (if it's possible with the current window size):

var element       = $("#some_element");
var elementHeight = element.height();
var windowHeight  = $(window).height();

var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);

@add9 2011-07-13 11:05:48

Check out the ScrollTo plugin. You can see the demo here.

I hope it helps.

@Chris Moschini 2013-03-27 03:48:34

I think it's worth noting that TimothyPerez's plugin is restricted to the y axis, while Ariel Flesler's (linked in this answer) is more of a kitchen sink supporting both x and y scroll, which can be important to consider for example when a modal dialog appears on mobile, or drawing attention to a specific part of a wide table or form on mobile.

@user669677 2014-02-12 14:22:28

$('html, body').animate({scrollTop: 
  Math.min( 
    $(to).offset().top-margintop, //margintop is the margin above the target
    $('body')[0].scrollHeight-$('body').height()) //if the target is at the bottom
}, 2000);

@Atharva 2013-12-24 11:35:37

If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

So all you need to do is: $("selector").get(0).scrollIntoView();

.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.

@Francisco Corrales Morales 2014-01-20 23:30:07

what is the .get(0) for?

@Atharva 2014-01-21 06:22:41

.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.

@Francisco Corrales Morales 2014-01-21 14:05:32

Thank you, can you give the diference between JavaScript's and JQuery's DOM element.

@RobW 2014-03-17 19:02:59

Could you also use $(selector)[0]?

@corbacho 2014-04-02 14:16:40

RobW, yes you can just use [0], but get(0) protects you against undefined or negative indexes. See the source: james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.fn.get

@Gavin 2014-06-23 18:59:25

If you don't want to use jQuery at all, just use document.getElementById('#elementID').scrollIntoView(). No use loading a ~100k library just to select an element and then convert it to regular JavaScript.

@Brian 2014-09-18 21:40:06

@Gavin I'm sure you meant that to be: document.getElementById('elementID').scrollIntoView()

@Gavin 2014-11-05 07:25:36

Yep, thanks! Obviously I use jQuery too much :)

@Walter Roman 2015-01-19 00:05:47

I think it's worth noting that this doesn't work for scrolling an element out from underneath elements laid over it, such as by position: absolute

@Arjun 2015-09-29 23:55:38

@FranciscoCorralesMorales You can not perform native JavaScript methods on jQuery Selectors, unless you store those jQuery selector into variables. Here, get(0) is used to change the selector to Vanilla JavaScript selector to perform native method of JavaScript on it.

@skrile 2015-12-08 15:34:31

I have a nested container situation and this was by far the cleanest solution. I lose the sexy scrolling bit but the offset tracking was crazy.

@Tejasvi Hegde 2016-11-16 15:46:10

Cool. But before using, make sure the browser supports this. As per Mozilla "This is an experimental technology"

@andreszs 2017-04-24 00:24:24

Experimental Technology = DO NOT USE UNDER ANY CIRCUMSTANCES

@Jonny 2017-07-04 13:54:09

I don't know why .animate() can be so unprecise. So I used scrollIntoView (the options do not yet work as stated) but scrolls to the correct item and position, tested in Chrome, Firefox and Safari, all fine! Even its "experimental" it WORKS rather than .animate() (not experimental) ;)

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

39 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

52 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5035652 View
  • 6317 Score
  • 69 Answer
  • Tags:   javascript arrays

38 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 675271 View
  • 2378 Score
  • 38 Answer
  • Tags:   javascript jquery

32 Answered Questions

[SOLVED] Add table row in jQuery

77 Answered Questions

[SOLVED] How do I detect a click outside an element?

  • 2008-09-30 13:17:12
  • Sergio del Amo
  • 997894 View
  • 2066 Score
  • 77 Answer
  • Tags:   javascript jquery

11 Answered Questions

26 Answered Questions

[SOLVED] Creating a div element in jQuery

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

Sponsored Content