Fadein and fadeout "back to top" button

Fadein and fadeout "back to top" button
0.0 0

#1

Hi, I’m trying to add “back to top” button which fadein while scrolling down and fadeout on the top of the page in my codepen project.
I read for hours about it and still can’t figure it out. I understand that I have to use Jquery and JS and I understant the general idea behind this, but I don’t know where to put each line. Where do I need to write the JS? Should I plant a Jquery?

Please, some advice :slight_smile:
Thanks…


#2

Can you give us a link to your project so we can see what you have tried so far?


#3

You never really need jQuery for anything. jQuery is just a JavaScript library that makes it easier to manipulate the DOM. I’ve never made a button such as what you are trying to make but it probably entails the following steps:

  • place a button mid-page to the right (or left, whichever you prefer) and use CSS to have its position fixed.
  • use either visibility: hidden or opacity: 0 as default so you don’t see it.
  • attach an event handler to the ‘scroll’ event using JavaScript
  • the function inside the event handler should modify the button by changing its style to either visibility: visible or opacity: 1
  • attach an event listener to your button
  • the function inside that event listener should either scroll page to top or simply link to top of page

Oh yeah if you want fade in fade out instead of JavaScript changing your style, add a class in your CSS that changes the opacity of your button to 1. The function inside the scroll event could add that class (using classList.add). Add a transition of a few hundred milliseconds to the CSS and the button will fade in.
If I have time I’ll make one myself and post an example. I admit it’s not the best explanation.


#4

You’ll need to know:

  1. The window’s inner height
  2. How far from the top you’ve scrolled
  3. The scroll height

You’ve hit the bottom of the page when 1 + 2 >= 3. You can modify first value if you want to know when you’re close to the bottom of the page instead. e.g. multiply the window’s inner height by 1.5.

If your page has sections you could also use them as some sort of trigger point.

EDIT: Whoops, just figured out I read it wrong and had it completely reversed. I’ll leave this here in case someone wants to do one where the button doesn’t appear until they’re at the bottom of the page.


#5

I just made one. I had problems with document.body.scrollTop - it wasn’t working for some reason.
It worked however with document.documentElement.scrollTop. That was a good exercise; thanks @lior.

Codepen: Scroll To Top