36

So this is the current code I have

$(document).ready(function() {
    $('.abouta').click(function(){
        $('html, body').animate({scrollTop:308}, 'slow');
        return false;
    });
    $('.portfolioa').click(function(){
        $('html, body').animate({scrollTop:708}, 'slow');
        return false;
    });
    $('.contacta').click(function(){
        $('html, body').animate({scrollTop:1108}, 'slow');
        return false;
    });
});

When you click a link e.g. 'abouta' it scrolls to that specific section of the page. I'd rather do a scrollTo and then the id of a div so that I don't have to keep changing the scrollTo position if I change padding etc. Is there any way?

Syscall
  • 19,327
  • 10
  • 37
  • 52
Jake
  • 1,137
  • 3
  • 11
  • 14

6 Answers6

110

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
  • 6
    I am surprised no one has commented in so long - the question as it stands, really asks for `.offset()` rather than `.position()` as a solution, right? The target div could be anywhere on the page, and `.position()` [returns the top offset relative to its container box](http://api.jquery.com/position/). So the above code will take you to the top of your document, if the target div is a first child of its parent. Or am I missing something? – sameers Jul 22 '16 at 01:54
  • Thanks Sameers, thats exactly the issue I was having. .offset() works a treat. – Dan382 Sep 24 '17 at 19:33
2

My solution was the following:

document.getElementById("agent_details").scrollIntoView();
DaFois
  • 2,197
  • 8
  • 26
  • 43
0

try this:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();
0

try this

    $('#div_id').animate({scrollTop:0}, '500', 'swing');
pirate
  • 21
0

Use this:

$('html').animate({ scrollTop: $("#yourDiv").offset().top-100 }, "slow");
David
  • 567
  • 4
  • 16
-2

if you want to scroll just only some div, can use the div id instead of 'html, body'

$('html, body').animate(...

use

$('#mydivid').animate(...
Fawas
  • 13
  • 2
  • 3
    Nope, `$('#div').animate({scrollTop:$('#div').position().top}, 'slow');` doesn't work. (Chrome 23). Better use `$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');` – bicycle Dec 14 '12 at 17:48