tholman / elevator.js

Finally, a "back to top" button that behaves like a real elevator.
http://tholman.com/elevator.js
6.63k stars 501 forks source link

Multiple Back To Top Support #140

Open oatmealr82 opened 4 years ago

oatmealr82 commented 4 years ago

I'm a true novice, and tried using the Back To Top feature multiple times on the same page. This was for an FAQ, which has multiple sections. At the end of each FAQ section I wanted to place a div elevator class that triggered the elevator. However, when I switched to querySelectorALL it broke the feature. I worry that I'm either doing something stupid, or that the code has to be updated to support using an array of elements on the same page? Love the 'easter egg' feature you made, but would love the readme to be updated to support multiple on the same page.

ljluestc commented 1 year ago
  1. HTML Structure:

Assuming your FAQ sections are structured like this:

<div class="faq-section">
  <!-- FAQ content -->
  <div class="elevator">Back to Top</div>
</div>

<div class="faq-section">
  <!-- FAQ content -->
  <div class="elevator">Back to Top</div>
</div>

<!-- ... and so on for other sections -->
  1. JavaScript:

You can use querySelectorAll to select all the .elevator elements and attach the elevator behavior to each of them. Here's how you might do it:

document.addEventListener("DOMContentLoaded", function() {
  const elevators = document.querySelectorAll(".elevator");

  elevators.forEach(elevator => {
    elevator.addEventListener("click", function() {
      // Scroll logic to move to the top of the FAQ section
      window.scrollTo({
        top: 0,
        behavior: "smooth"
      });
    });
  });
});

This code iterates through each .elevator element, adding a click event listener to each one. When an elevator is clicked, it smoothly scrolls to the top of the corresponding FAQ section.