How to go to a specific element on page?
To explicitly specify where to scroll, use anchor links. Provided a unique ID, you can create a hyperlink using the fragment identifier #
. For example, clicking <a href="#section">Jump to Section</a>
, will land you to <div id="section">...Target Content...</div>
.
Example:
On click, the hyperlink literally jumps to the HTML element #section
, at the top of the window.
Javascript and scrolling: A twisted tale
For manually controlling the scrolling on your website using JavaScript, refer to the below methods:
Plain and simple: The scrollIntoView() method
The function element.scrollIntoView()
allows you to navigate to an element by aligning it to the top of the viewport.
However, if you intend to align the element with the bottom instead of the top, pass false
as a parameter:
A word of caution: Ensure that the element exists before calling scrollIntoView()
. This can save you from a potential TypeError.
Splendid scrolling with jQuery
Prefer a smooth ride to your section? Use jQuery animate()
, combine it with scrollTop()
, and voila!
This will cause the page viewport to animate the scrolling action over a 1000 milliseconds duration.
Custom-made luxury: A jQuery plugin
To add further flexibility and allow chaining, create a custom jQuery plugin:
You can use the plugin in a jiffy:
Elementary visibility
Before you start labelling visibility as an illusion, note this: ensure the element is visible on the page. Hidden elements such as those with display: none
or visibility: hidden
styles won't make it to the screen, even post scrolling.
IFrame on iOS: A different ball game
Working with iframes on iOS devices could be tricky. Thankfully, scrollIntoView()
has some tricks up its sleeves – or rather, iPhone-specific adjustments for better user experience.
Nimble linking: Hashchange event
Anchor tags are consistent, but they aren't solitary. Remember the infamous hashchange event. It can cause a ripple. So, ensure the scrolling and hash events coexist harmoniously.
Not deja vu: Page load and scrolling
Finally, code in jQuery(document).ready()
your scripts to ensure the scroll functions are ready post-page load, eliminating any risk of untimely events binding.
Was this article helpful?