Scroll-to-Position Choices
There are two choices to easily scroll a web page to a specific point within a browser window.
-
The fragment identifier:
When a URL contains an octothorpe ("
#
" — also referred to as a pound sign or hash mark) followed by a series of characters, the series of characters are called a fragment identifier.Immediately after the page has loaded, or perhaps sooner, the page is scrolled to the element with an id value matching the fragment identifier.
As an example, the URL
https://example.com/#place
would scroll down to where there is a
<div id="place">
on the page.
-
The JavaScript scrollIntoView() function:
After a page has been loaded, or before complete load in some situations, JavaScript can be used to scroll the browser window to a point on the page where a certain element is visible — in view within the browser window.
As an example, the JavaScript code
document.getElementById("place").scrollIntoView()
would scroll down so the element
<div id="place">
is visible on the page.
The Willmaster Library Scroll Into View article describes how to use the
scrollIntoView()
function.
Note: The name
attribute as a scroll-to position (for any scroll-to method) is not supported in HTML5.
Choosing
Of the two choices, the primary functional differences are:
-
The URL method can be used only when a page loads.
-
The
scrollIntoView()
method can be used at any time while the page is in the browser window.
The following suggestions are general.
Uses for the URL method —
The URL method can be used only when a link is tapped or a bookmark is activated.
The browser quickly scrolls to the element with the identifier as the id value. The scrolling occurs as the page loads or as soon as it finishes loading.
No JavaScript is required.
The URL with the identifier fragment can be bookmarked. The browser will scroll to that point on the web page whenever the bookmark is used (provided the id with the identifier is still on the page). If the fragment must not be bookmarked with the rest of the URL, then scrollIntoView()
may be a better choice.
Uses for the scrollIntoView()
method —
This requires JavaScript. It also does not include the scroll within a bookmark link.
The scrollIntoView()
method may be invoked at any time so long as the page is in the browser. Reasons for using this method generally are related to scrolling to another point on the page when the user asks for it — when a certain icon is tapped, for example.
As noted earlier, the Willmaster Library Scroll Into View article describes how to use the scrollIntoView()
function.
The two methods each have their attractions and detractions. Probably one or the other will work well when you need the page to scroll to a certain point.
(This article first appeared with an issue of the Possibilities newsletter.)
Will Bontrager