Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
140byt.es -- Click ↑↑ fork ↑↑ to play!

Scroll To

Permit to scroll into the document to an element passed as first argument.

function(
e, // the HTMLElement to scroll to
x, // set the X position of 'e'
y // set Y position of 'e'
) {
x=y=0; // set the default values for X and Y in the same time
do {
x += e.offsetLeft; // add the X position of the current HTMLElement 'e'
y += e.offsetTop // same thing for Y
} while(e=e.offsetParent); // we need to add the offsetParent's coordinates too (if they exist)
window.scrollTo(x,y); // now we know the coordinates, so we can scroll to the HTMLElement 'e'
}
function(e,x,y){x=y=0;do{x+=e.offsetLeft;y+=e.offsetTop}while(e=e.offsetParent);window.scrollTo(x,y)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "scrollToElement",
"description": "Permit to scroll into the document to an element passed as first argument.",
"keywords": [
"html",
"dom",
"functional",
"animation"
]
}
<!DOCTYPE html>
<title>Scroll To</title>
<button onclick="scrollToElement(document.getElementById('test'))">Click me!</button>
<div id="big-one" style="width:5000px;text-align:right;"><span id="test">Come here!</span></div>
<script>
var scrollToElement = function(e,x,y){x=y=0;do{x+=e.offsetLeft;y+=e.offsetTop}while(e=e.offsetParent);window.scrollTo(x,y)};
</script>
@Yaffle

This comment has been minimized.

Copy link

@Yaffle Yaffle commented Jul 30, 2011

what about DOM:
element.scrollIntoView() ?

@Yaffle

This comment has been minimized.

@Aymkdn

This comment has been minimized.

Copy link
Owner Author

@Aymkdn Aymkdn commented Jul 30, 2011

@Yaffle, I don't think it works on all browsers

@Aymkdn

This comment has been minimized.

Copy link
Owner Author

@Aymkdn Aymkdn commented Jul 31, 2011

Ok so I've tested on several browsers and scrollIntoView() seems to work (even if on some forums they say it doesn't work on Opera or IE8: in my tests it does work)
Thanks @Yaffle for let me learn about this function I didn't know before...

@Yaffle

This comment has been minimized.

Copy link

@Yaffle Yaffle commented Jul 31, 2011

Unfortunately, element.scrollIntoView isn't scroll smoothly...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment