Last active
February 19, 2018 05:39
-
-
Save tkfm-yamaguchi/80d64caee42950efa98cc3b9f95c7b1d to your computer and use it in GitHub Desktop.
scroll to the specific element programatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>すくろーる♡</title> | |
<style type="text/css"> | |
#outer { | |
border: 1px solid #000; | |
height: 400px; | |
overflow-y: scroll; | |
position: relative; | |
} | |
</style> | |
</head> | |
<body> | |
<p> | |
<input type="button" id="beerButton" value="🍺"></input> | |
<input type="button" id="sushiButton" value="🍣"></input> | |
</p> | |
<div id="outer"> | |
<div id="inner"> | |
<ul> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li id="beer">🍺🍺🍺</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li>...</li> | |
<li id="sushi">🍣🍣🍣</li> | |
</ul> | |
</div> | |
</div> | |
<script type="text/javascript"> | |
function scrollTo(target, parent) { | |
if (target.offsetParent !== parent && target.offsetParent !== parent.offsetParent) { | |
throw 'target.offsetParent should be a parent or the same as parent.offsetParent'; | |
} | |
const parentOffset = 0; | |
if (target.offsetParent === parent.offsetParent) { | |
parentOffset = parent.offsetTop; | |
} | |
parent.scrollTop = target.offsetTop - parentOffset; | |
} | |
document.addEventListener('DOMContentLoaded', () => { | |
const outer = document.getElementById('outer'); | |
const beer = document.getElementById('beer'); | |
const sushi = document.getElementById('sushi'); | |
const sushiButton = document.getElementById('sushiButton'); | |
const beerButton = document.getElementById('beerButton'); | |
sushiButton.addEventListener('click', () => { | |
scrollTo(sushi, outer); | |
}); | |
beerButton.addEventListener('click', () => { | |
scrollTo(beer, outer); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment