When creating web pages, adding a button that allows users to go to the bottom or return to the top of your page (also known as a Long Scroll) will make their experience smoother.
Think of those websites where the page keeps loading and loading, such as online clothing stores. You start browsing through their clothing items: skirts, tops, dresses and the page keeps growing longer and longer.
Soon you are at the bottom of the page, very far away from the starting point and begin crawling your way back up… I am sure you have had the same thought I have had in the past: ‘I wish I could go all the way up in one click!’
Note, it is possible to use the ‘home’ and ‘end’ keys to do this, but not everybody will be aware of this and mobile devices lack this feature.
Let’s break down this feature so we can help enhance our browsing experience. We will first go with the HTML:
Initially, when the page first loads, the buttons are not visible by setting the attribute hidden to true on these elements.
Note, I have used unicodes to represent the arrows: ↑ / ↓.
Now, let’s move on to the CSS file, where we are adding a basic background colour to the section and some height only to show the effect of scrolling up and down. If you had other elements on the page, you would probably not need to set a height:
As there are two buttons, you can give them basic common aspects:
I like keeping consistency, so I want them to look alike. Even for the hover effects:
However, you will need to give each of the buttons separate styling, especially here, as we want to place them in a particular position:
Of course, you can modify these positions depending on your needs.
Finally, on to the JS file, where we will start by targeting the buttons:
Then, you need to set the conditions for the buttons to appear or disappear depending on how far into the page the user is (on this occasion, anytime the user scrolls down 20px):
Note, <document.body.scrollTop> refers to the action of scrolling on the page whereas <document.documentElement.scrollTop> refers to any potential elements you have on the page (in this example, none).
After that, all we are missing is specifying the function that will get called whenever you click on either button:
The output for the above coding, should look like this:
For a full, working example, please visit this codepen. Play around with it, you can see the buttons appearing and disappearing, they can take you all the way down or all the way up!
Happy coding to you all and don’t forget to be considerate with each other!