Issue with Swiper JS: The buttons on pages three and beyond are unresponsive

I'm having trouble with the functionality of the "Back" button on pages 2 and 3 of my website. Can anyone help me figure out why it's not working?

My goal is to create a website that resembles a game menu, similar to Deus Ex The Fall. I'm using Swiper JS to create a slider with parallax effects for the background images. However, something seems to have gone wrong.

const swiper = new Swiper('.swiper', {
  // Optional parameters
  direction: 'horizontal',
  
  parallax: true,
  

});

document.querySelector('.back').onclick = () => {
  swiper.slideTo(0)
}

document.querySelector('.page1').onclick = () => {
  swiper.slideTo(1)
}

document.querySelector('.page2').onclick = () => {
  swiper.slideTo(2)
}

document.querySelector('.page3').onclick = () => {
  swiper.slideTo(3)
}
...
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Testttt</title>
    <link rel="stylesheet" href="./swiperjs/swiper-bundle.min.css">
    <link rel="stylesheet" href="./index.css">
    ...
<body>
            <div class="swiper">  
              <div class="swiper-wrapper">  
                <div class="parallax-bg" style="background-image:url(./images/panorama.jpg)" 
                data-swiper-parallax="100%"></div>
                    <!-- Slides --> 
                    <div class="swiper-slide">
                        <h1>Page 0</h1>
                      <div class="buttons">
                        <button class="page1">Page1</button>
                        <button class="page2">Page2</button>
                        <button class="page3">Page3</button>
                      </div>
                    </div>

The "Back" button works correctly on Page 1

                    <div class="swiper-slide">
                        <h1>Page 1</h1>
                      <div class="buttons">
                        <button class="back">Back</button>
                      </div>
                    </div>

However, the buttons are no longer functioning from this point onwards

                    <div class="swiper-slide">
                        <h1>Page 2</h1>
                      <div class="buttons">
                        <button class="back">Back</button>
                      </div>
                    </div>
                    <div class="swiper-slide">
                        <h1>Page 3</h1>
                      <div class="buttons">
                        <button class="back">Back</button>
                      </div>
                    </div>  
            </div>
        </div>

    <script src="./swiperjs/swiper-bundle.min.js"></script>
    <script src="./index.js"></script>
</body>
</html>

Answer №1

Instead of using querySelector to set the event listener, try using querySelectorAll which will give you all elements with that selector:

const els = document.querySelectorAll('.back');
els.forEach ( el => {
  el.onclick = () => {
    swiper.slideTo(0)
}
});

You may need to adjust the parameter passed in slideTo accordingly. You can also consider using a for loop instead of forEach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with a class component stating that "this.setState is not a function

I am currently learning React JS and encountered an error when calling my first API in React. I keep getting the message "Unhandled Rejection (TypeError): this.setState is not a function." I have been trying to troubleshoot this issue on my own but haven ...

Text-color in the v-tooltip

Is there a way to change the text color of v-tooltips components without affecting the tooltip background color? I attempted to inspect the element, but the tooltip only appears on hover, making it impossible to inspect. Below is the code snippet: < ...

Tips for incorporating multiple classes in Material UI by utilizing the classes props

When using the css-in-js technique to apply classes to a react component, how can I add multiple classes? Below is an example of the classes variable: const styles = theme => ({ container: { display: 'flex', flexWrap: 'wrap&apo ...

Adjust the child element's value by referencing the parent class name

I need to update the content of child elements within an HTML file based on the class name of their parent element, using JavaScript. While I have successfully achieved this for static values by creating a TreeWalker for text nodes, doing the same for dyn ...

Tips on making the form validation script operational

After developing a form alongside a form validation script to ensure that all fields are completed, the name and city sections only contain letters, while the age and phone sections solely include numbers, issues have arisen. It seems that despite the cons ...

Creating a Drop-down Menu Item using React Material UI

I am experiencing an issue with displaying a MenuItem in my Dialog2 within my React app. Despite setting the zIndex: 1900 to a higher value than the two dialogs, the MenuItem remains hidden behind the dialogs instead of appearing at the front. Please revi ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

Can you provide a list of factors that influence coverage? Additionally, is there a specific algorithm available for calculating

As part of my Angular project, I am currently focusing on writing unit test cases using the Jasmine Framework and Karma. To ensure thorough testing coverage, I am utilizing Coverage-html (Istanbul). When it comes to coverage, there are several important t ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

What is causing the initial activation of the <button> within a form?

Within my <form>, I have included 2 submit buttons. The first button looks like this: <button class="regular" id="geocodesubmit" style="height:40px;">Set Location</button> The second button looks like this: <button type="submit" ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

Creating dynamic dropdowns with Ajax and HTML on the code side

I have developed a script that generates a drop-down menu and updates the .box div with a new color and image. Below is the HTML & Java code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div> ...

Generate a flexible JSON array in VB.NET

Looking to generate a flexible array that can be converted into a JSON array for visualization with Morris charts. The usual approach in VB.NET is as follows: Dim xArray(2) xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 160 ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Set a maximum height for the <td> element within a table, regardless of the length of the text in neighboring cells

Here is the situation I'm dealing with: In the thread, the postbit (blue box with avatar inside) looks fine for most posts (the first three). However, the fourth postbit is vertically elongated due to longer post content. I have been trying differe ...

Verifying the presence of an ID within a jquery cookie

I encountered an issue with this code on a product page. Whenever I click the save button, it stores the product ID in a jQuery cookie. The IDs are stored in the cookie like this: 1,2,3,4... If an ID is already in the cookie, there seems to be a problem a ...

Ways to retrieve several parameters from a controller using Ajax Jquery in Codeigniter

I need to retrieve a list of images from a folder based on a specific ID. Currently, I am able to get the file names but I also require the upload path. Is there a way to obtain both sets of data using a single function? Javascript Code: listFilesOnServ ...

What could be causing the client to not receive the socket.io broadcast in the designated rooms?

My client isn't receiving the broadcast sent to the room. I have tried replacing socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser); and it works, but I prefer using rooms in this scenario. Any ass ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...