Arrow – Scroll Back to the top of the page

What will we be doing?

You can check the full code and working version here: https://codepen.io/lovetocodex/pen/wppvBP

What will you learn?

  • How the function ‘setTimeout’ and ‘setInterval’ function works.
  • How to listen to click and scroll event.
  • How to make arrow feature.

 

The HTML

The HTML is super simple. We will create a button, and inside the button, we will put an icon.

<button class="arrow-up">

    <i class="fa fa-chevron-up"></i>

</button>

 

To get the icon working, include this link between your head tags.

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

 

 

The CSS

We will focus on the important aspect of the CSS here. For now, this will do.

The key concept when doing this in CSS is that we want to have it display none and put opacity to 0 as well as visibility – I will explain that later. In general, you can have display none and opacity together, but with JavaScript magic, we will make it work.

Another aspect of the button is that we need to position it fixed to be always in the same place.

Write the code in your CSS files 😊

.arrow-up {

    font-size: 17px;
    font-weight: 500;
    line-height: 15px;

    position: fixed;
    z-index: 9000;
    right: 25px;
    bottom: 20px;

    display: none;
    visibility: hidden;
    overflow: hidden;

    padding: 10px 13px;

    cursor: pointer;
    transition: .15s ease-in-out;
    text-align: center;



    opacity: 0;
    color: #fb9b26;
    border: 2px solid transparent;
    border-radius: 2px;
    background-color: white;

}

 

Let’s write the JavaScript

Alright! Now the fun part. JavaScript!

Every challenge or problem is very complex and hard – only if it’s completed.

We need to break things apart and think through it, what will need to be done and how will we do it. It’s a step-by-step process.

Firstly, what do we want to do?

We want the arrow to face in/appear after scrolling a certain height, and once it’s clicked, it should fade out/disappear and scroll us to the top.

 

Planning out

We want to select the arrow in our JavaScript.

After 500px we want to show it. We can probably make a function, ‘toggleArrow’ and write the appropriate code there.

We want the speed of how fast it will scroll us up, we’ll name it ‘scrollStep’.

Lastly, but not least, we want it needs to scroll up. So we can probably make a function named ‘scrollToTop’

We also need some event listeners, so the browser knows when we clicked what.

 

If we have missed anything, we can always go back and upgrade our code.

 

Let’s write our code – setting the main parts

We want to always load the code after the HTML and CSS have loaded.

 

window.onload = function() {

    // Variables
    var arrowUp;
    var intervalidId;

    // Functions
    function toggleArrow() {

    }

    function scrollStep() {

    }

    function scrollTop() {

    }

}

 

 

Feels satisfying huh? 😊

Adding the missing CSS to the arrow

Let’s add the missing CSS to the arrow. Now that we are going to do JS, we will need it.

The visibility class means that we can’t hover over it, it will not take any effects.

The opacity means that we can transition it into fade in/out.

The display none/block means that the element is going to either display or not.

 

Toggling the arrow

 

To toggle the arrow, first, we need to select it.

var arrowUp = document.querySelector(‘.arrow-up’);

Let’s add this code at the end of our file

window.addEventListener(‘scroll’, toggleArrow);

We first target the window, we want to listen if anything happens to it. But what do we want? When someone scrolls.

Okay, the window is no listening to scrolling, but what now? We want to use a function, toggleArrow that we will write right now.

 

Now that we got the arrow, let’s start to write the code inside the ‘toggleArrow’ function.

Let’s remember that our arrow is hidden and displayed to none.

We need to get the window, and when we scroll past 500px, do something.

What do we want to do? We need to get the window view of the Y-axis scroll. Then if it’s less or equal to 500px, do this, else do something else.

Don’t forget to add the ‘e’ between the toggleArrow function – that means we will pass the event. The even is ‘scroll’, as we want this to happen when we scroll past 500px.

 

function toggleArrow(e) {

    if (window.scrollY >= 500) {
              
    } else {

    }

}

 

 

What do we want to do? We want to show the arrow, so let’s add the class we just added to display block and opacity.

function toggleArrow(e) {

    if (window.scrollY >= 500) {

        arrowUp.classList.add('is-block');
        arrowUp.classList.add('is-opacity');

    } else {

    }

}

 

 

But it just appears! Yes, yes it does! Remember that the the display block/none CSS property can’t be animated with the opacity? Yep! That’s it! We need to work around that.

Hmmm, what if we display it block, and after certain time we display the other class? That sounds good to me!

 

if (window.scrollY >= 500) {

    arrowUp.classList.add('is-block');

    setTimeout(function() {
        arrowUp.classList.add('is-opacity');
    }, 10);



    } else {

        arrowUp.classList.remove('is-opacity');
    }

}

 

That code will do the magic.

Let me explain what’s happening.

We used a ‘setTimeout’ build in JS function. The function executes the code after a certain amount of time. It counts in milliseconds – this function executes after waiting  a specific number of milliseconds, unlike the ‘setInterval’ but it repeat the function in infinity.

The number at the end, says how long to wait before execute it? 10milliseconds which is 0.01 while 1000milliseconds is 1second.

 

The first part of the battle won!

We did it! We won the first half of the battle! The arrow shows after 500px by fading in, and if we scroll less than 500px the arrow will fade out!

This is the code you should have as of now:

window.onload = function() {

               
// Variables
var arrowUp = document.querySelector('.arrow-up');

               
    // Functions
    function toggleArrow(e) {

      if (window.scrollY >= 500) {

        arrowUp.classList.add('is-block');
        setTimeout(function() {
            arrowUp.classList.add('is-opacity');
        }, 10);

      } else {

          arrowUp.classList.remove('is-opacity');

      }

    }

                   
    function scrollStep() {

    }
                  
    function scrollToTop() {

    }
                  
    // Event listeners
    window.addEventListener('scroll', toggleArrow);
 

}

 

Adding the automatic scroll to top

Let’s add a variable just below the ‘arrowUp’ var.

var intervalId = 0;

We will use that variable to keep track on how deep the screen is scrolled.

 

The function ‘pageYOffset’  takes two parameters. The first one is x, which is horizontal, and the second one is Y, which is vertical.

 

We want to scroll the page to the top. Inside the function ‘scrollStep’ let’s add this code:

window.scroll(0, window.pageYOffset - 50);

 

We use the window scroll to scroll to a particular place to the window. Remember X and Y coordinates? We want it to scroll to the top, so the first parameter will be left to 0, and the other parameter will be set to go -50px(which we don’t want that, but it will give us a nice effect if we repeat it multiple times).

We should have this code:

function scrollStep() {

    window.scroll(0, window.pageYOffset - 50);

}

 

 

Let’s repeat that function so the page scrolls to the top. In the function ‘scrollToTop’ write this:

function scrollToTop() {

    intervalId = setInterval(scrollStep, 8.36);

}

 

Remember the variable intervalId? We need to store the value that will be changed. We need to keep a track of it, and store it. That way the browser won’t forget about it.

We are changing that 0 to something.

The variable: intervalId = 0, is no longer a 0. Now we are running the ‘scrollStep’ function every 8.36miliseconds infinite.

Before you hit that button, there is one last thing we need to do, we need to listen if someone hits the button.

Let’s ad an event listener to it.

arrowUp.addEventListener(‘click’, scrollToTop);

We select the arrow, we listen if someone clicks to it, and if they do, we execute the ‘scrollToTop’ function.

Great!

 

Oh! You have the same problem as me? Wait, what? We can’t scroll down now, it seems that the function is always running – you’re probably thinking that’s because the infinite timing is always running.

And you’re right!

Let’s stop it once it hits the top.

In the scrollStep function, we need to write the logic for it.

if (window.pageYOffset === 0) {
    clearInterval(intervalId);
}

 

Okay, so we get the window, we check the coordinates of the window, and if the coordinates of the window is 0(zero) (the start of the page), we want to reset the intervalId (since that’s t where the function is updating the value).

How do we clear it?

By using the clearInterval function – is’s basically a build in JS function that stops anything that’s changing.

This is our function:

function scrollStep() {
    if (window.pageYOffset === 0) {
        clearInterval(intervalId);
    }    
    window.scroll(0, window.pageYOffset - 50);
}

 

 

Conclusion

You can check the full code and working version here: https://codepen.io/lovetocodex/pen/wppvBP

window.onload = function() {
    
    // Variables
    var arrowUp = document.querySelector('.arrow-up');
    var intervalId = 0;
    
    // Functions
    function toggleArrow(e) {

        if (window.scrollY >= 500) {
            arrowUp.classList.add('is-block');

            setTimeout(function() { 
                 arrowUp.classList.add('is-opacity');
            }, 10);

            } else {
                arrowUp.classList.remove('is-opacity'); 
        }

    }

    function scrollStep() {
            if (window.pageYOffset === 0) {
                    clearInterval(intervalId);
            }
            window.scroll(0, window.pageYOffset - 50);
    }

    function scrollToTop() {
            intervalId = setInterval(scrollStep, 8.36);
    }


    // Event listeners
    arrowUp.addEventListener('click', scrollToTop);
    window.addEventListener('scroll', toggleArrow);
    
}

 

Comment below! 🙂

Happy Coding!

Meet the author

Meet the author

Aurelian Spodarec

Front-end WordPress developer that blogs about web development. I like using the right tools for the job. In my spare time, I enjoy cooking healthy food and then eating it. Delicious!

Comments