Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple Back To Top Support #140

Open
oatmealr82 opened this issue Aug 2, 2020 · 1 comment
Open

Multiple Back To Top Support #140

oatmealr82 opened this issue Aug 2, 2020 · 1 comment

Comments

@oatmealr82
Copy link

oatmealr82 commented Aug 2, 2020

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
Copy link

  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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants