Skip to content

Instantly share code, notes, and snippets.

@Aymkdn
Forked from 140bytes/LICENSE.txt
Created July 29, 2011 17:29
Show Gist options
  • Save Aymkdn/1114275 to your computer and use it in GitHub Desktop.
Save Aymkdn/1114275 to your computer and use it in GitHub Desktop.
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
Copy link

Yaffle commented Jul 30, 2011

what about DOM:
element.scrollIntoView() ?

@Yaffle
Copy link

Yaffle commented Jul 30, 2011

@Aymkdn
Copy link
Author

Aymkdn commented Jul 30, 2011

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

@Aymkdn
Copy link
Author

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
Copy link

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