An Alternative to Hash URLs with ScrollIntoView()
I don’t know much JavaScript, but I do love it when I discover a new trick for doing something simple. The scrollIntoView()
method is a very handy addition to JS. So, what’s it for?
Firstly, I must admit I don’t like the name, because it doesn’t really have much to do with scrolling. It’s just a simple way to make a page jump to a specified element when the page loads. So it’s a bit like ‘hash URL’—that is, a URL like mypage.html#special
, which takes you to an element on the page with an ID of #special
.
Hash URLs are handy if you are clicking a link to get to the page, but they aren’t much use when going directly to the page—which is where scrollIntoView()
comes in.
Let’s say you have an element in the middle of your page—with an ID of #special
—that you want to appear at the top of the screen when the page loads. You can achieve that by adding this simple script to your page:
<script>
var special = document.getElementById("special");
special.scrollIntoView(true);
</script>
Here’s a demo (scroll up to see that this #special
element is not at the top of the HTML):
The default is for the targeted element to appear at the top of the screen, so it’s not necessary to include true
. If you’d prefer the targeted element to appear at the bottom of the page, use false
instead:
<script>
var special = document.getElementById("special");
special.scrollIntoView(false);
</script>
That’s certainly something you can’t do with a hash URL. Here’s a demo:
More Flexible than Hash URLs
Unlike with hash URLs, you can target elements without a specific ID. With the help of querySelector
, for example, you could easily target any element. Here’s how you could target an element with a class of .special
:
<script>
var special = document.querySelector(".special");
special.scrollIntoView(true);
</script>
Of course, you’d have to be careful to use that class just once. Anyway, here’s a demo of that:
Browser Support
Amazingly, scrollIntoView()
is supported as far back as IE7, so there’s no problem in this regard.
Here are some further references: