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.


@object-Object 2018-12-20 17:22:12

I know a way without jQuery:


Edit: It's been two years and I'm still randomly getting reputation from this post lmao

Edit 2: Please don't edit my comment without asking me.

@Jan 2020-06-26 12:54:28

Never heard of this function in 15 years of JavaScripting! :-o

@itoctopus 2020-07-16 12:05:28

This function worked in one of the most restrictive pages (absolute divs, 100% heights, etc...) where the normal jquery function didn't work (it didn't return an error, but it didn't work).

@Kamil Kiełczewski 2020-01-08 11:16:29


subject.onclick = e=> window.scroll({ top: submit.offsetTop, behavior: 'smooth'});

subject.onclick = e=> window.scroll({top: submit.offsetTop, behavior: 'smooth'});
.box,.foot{display: flex;background:#fdf;padding:500px 0} .foot{padding:250px}
<input type="text" class="textfield" value="click here" id="subject" name="subject">

<div class="box">
  Some content

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

<div class="foot">Some footer</div>

@Edvard Åkerberg 2019-06-20 13:59:56

This is the way I do it.

document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })

Works in any browser.

It can easily be wrapped into a function

function scrollTo(selector) {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })

Here is a working example

$(".btn").click(function() {
  document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })
.btn {margin-bottom: 500px;}
.middle {display: block; margin-bottom: 500px; color: red;}
<script src=""></script>

<button class="btn">Scroll down</button>

<h1 class="middle">You see?</h1>

<div id="scrollHere">Arrived at your destination</div>


@OG Sean 2019-08-04 02:19:35

Pretty short and sweet. One thing to note - I think this only scrolls it into view (could be at the bottom of the viewport) rather than scrolling it to the top of the viewport, as setting scrollTop does.

@Minguocode 2019-03-19 15:25:41

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

    $('html, body').stop().animate( {
      'scrollTop': $target.offset().top-40
    }, 900, 'swing', function () {
      window.location.hash = target;
    } );
  } );
} );
<script src=""></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>

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

@stardust4891 2019-01-17 19:58:55

Updated answer as of 2019:

    scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
}, 'fast');

@ali6p 2019-11-19 14:43:49

You should this selector for body: [document.documentElement, document.body] AND No need body offset in the equation. $('#subject').offset().top is enough.

@Polaris 2018-11-07 08:51:12

This worked for me:

var targetOffset = $('#elementToScrollTo').offset().top;
$('#DivParent').animate({scrollTop: targetOffset}, 2500);

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

This is Atharva's answer from: 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.

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

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

This will not work in all cases. See…

@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 ' (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:…

@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…

@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: 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 Mijatović 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.

@weltschmerz 2019-12-07 18:14:55

$(window.location.hash) won't work for hashes that fail to meet jQuery's regex id detection. For example, hashes that contain numbers. It's also a bit dangerous; the input's format should be validated so you don't end up selecting a different element.

@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.

    $.fn.animateScroll = function(){
            selector = $($(this).attr('scroll'));
            $('html body').animate(
                {scrollTop: (selector.offset().top)}, //- $(window).scrollTop()

// RUN
jQuery(document).ready(function($) {

// <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);

@a11r 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;

  scrollTop: pos

@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


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.

@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 (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 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?

@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

@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…

@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.

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

@AlexRindone This demo works in Chrome Site with old demo isn't working now.

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


// 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(){
    $('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.


Here is what I have ended up with

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

All body content wired up with a #content div

<div id="content">

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

You really shouldn't use user agent sniffing.

@daliaessam 2019-04-06 21:55:30

Add word-break: break-all; to your CSS element that is in trouble. Android/iOS webview jQuery.animate({scrollTop: y}) position Incorrect.…

@svnm 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')

/* 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 {

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

function getElementOffset(element) {
  let de = document.documentElement
  let box = element.getBoundingClientRect()
  let 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) {
  $("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();

@jayasurya_j 2018-12-26 17:48:26

e.preventDefault() however doesn't update the hash in the url on clicking, its always an url without hash

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

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

    $('html, body').stop().animate( {
      'scrollTop': $target.offset().top-40
    }, 900, 'swing', function () {
      window.location.hash = target;
    } );
  } );
} );
<script src=""></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>

<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>');

  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()

@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


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:

  #F > *
    width: 100%;

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



@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":

// 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;

        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;

        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)

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

@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:


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);

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

$('html, body').animate({scrollTop: 
    $(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:

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.

@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:

@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()

@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


@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) ;)

@dsturbid 2019-01-24 10:55:24

93% of global users now have support for this without smooth scroll

@forresthopkinsa 2019-09-19 00:06:31

70% of global users can use smooth scrolling with scrollIntoView(options: { behavior: 'auto' | 'smooth', block: 'start' | 'center' | 'end' | 'nearest', inline: 'start' | 'center' | 'end' | 'nearest' })

Related Questions

Sponsored Content

66 Answered Questions

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

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6921497 View
  • 8490 Score
  • 96 Answer
  • Tags:   javascript arrays

42 Answered Questions

[SOLVED] Scroll to the top of the page using JavaScript?

  • 2009-07-17 17:59:09
  • KingNestor
  • 1713116 View
  • 1618 Score
  • 42 Answer
  • Tags:   javascript scroll

80 Answered Questions

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

41 Answered Questions

[SOLVED] How to check if element is visible after scrolling?

42 Answered Questions

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

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 752346 View
  • 2798 Score
  • 42 Answer
  • Tags:   javascript jquery

38 Answered Questions

[SOLVED] Add table row in jQuery

57 Answered Questions

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

41 Answered Questions

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

Sponsored Content