Clickable arrows in slideshow failing to navigate properly

As I embark on my journey in programming and work on creating my own website using Kirby, I encountered a challenge. I attempted to integrate a carousel slider into my website following a tutorial at https://youtu.be/9HcxHDS2w1s. Despite meticulously replicating the steps outlined in the tutorial, I faced an issue where the arrows for navigating the slides were unresponsive. The rest of the carousel appears to be functioning correctly, leaving me to suspect that the problem lies with the links.

Here's the HTML code:

    <div class="carousel-h" data-carousel>
        <button class="carousel-button-h prev-h" data-carousel-button="prev-h">
        <img src="<?= url('assets/icons/button-prev.svg') ?>"></button>
        <button class="carousel-button-h next-h" data-carousel-button="next-h">
        <img src="<?= url('assets/icons/button-next.svg') ?>">
        </button>
        <ul data-slides> 
            <li class="slide-h" data-active>
                <img src="images/Fokuss_Poster_web.jpg" alt="">
            </li> 
            <li class="slide-h">
                <img src="images/Rebooth_mockup_prints_web.jpg" alt="">
            </li>  
            <li class="slide-h">
                <img src="images/Kushim_Thumbnail_web.jpg" alt="">
            </li>  
            <li class="slide-h">
                <img src="images/Savo_Mockup_web.jpg" alt="">
            </li>
            <li class="slide-h">
                <img src="images/Foto_Zine_2Sem_12-web.jpg" alt="">
            </li>
            <li class="slide-h">
                <img src="images/Subspace_Mockup_web_0.jpg" alt="">
            </li>
            <li class="slide-h">
                <img src="images/Zeitung_Vision_06-web.jpg" alt="">
            </li>
        </ul>
    </div>
</section>

This is the JavaScript code:


buttons.forEach(button => {
    button.addEventListener("click",  () => {
        const offset = button.dataset.carouselButton === "next" ? 1 : -1
        const slides = button
        .closest("[data-carousel]")
        .querySelector("[data-slides]")

    const activeSlide = slides.querySelector("[data-active]")
    let newIndex = [...slides.children].indexOf(activeSlide) + offset
    if (newIndex < 0) newIndex = slides.children.length -1
    if (newIndex >= slides.children.length) newIndex = 0

    slides.children[newIndex].dataset.active = true
    delete activeSlide.dataset.active
    })
})

And here is the CSS code:

.carousel-h {
    width: 100vw;
    height: 100vh;
    position: relative;
}

.carousel-h > ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

.slide-h {
    position: absolute;
    inset: 0;
    opacity: 0;
    transition: 200ms opacity ease-in-out;
    transition-delay: 200ms;
}

.slide-h > img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}

.slide-h[data-active] {
    opacity: 1;
    z-index: 1;
    transition-delay: 0ms;
}

.carousel-button-h {
    position: absolute;
    background: transparent;
    z-index: 999;
    border: none;
    font-size: 3rem;
    top: 50%;
    transform: translateY(-50%);
    color: rgba(0, 0, 0, 1);
    border-radius: .25rem;
    padding: 0 .5rem;
}

.carousel-button-h.prev-h {
    left: 1rem;
}

.carousel-button-h.next-h {
    right: 1rem;
}

I have tried replacing the arrow images from the tutorial with alternate SVG icons but to no avail. Even employing the HTML code snippets for arrows from toptal did not resolve the issue. Despite my efforts to identify the error, I remain unable to pinpoint it, seeking assistance and guidance. Thank you!

Answer №1

Your JavaScript code is causing an error due to using forEach on an undefined variable. It seems that you forgot to define the 'buttons' variable in your code. Here's how you can fix it:

  1. Start by selecting all buttons on the page using getElementsByTagName.
const buttons = document.getElementsByTagName("button");
  1. After selecting all buttons, remember that the type of the 'buttons' variable will be an object, and you cannot use forEach on an object. To make it work, you need to convert the object into an array like this:
const buttonsList = Array.prototype.slice.call(buttons);

Now that you have your buttons list as an array, you can proceed with your code implementation:

const buttons = document.getElementsByTagName("button");
const buttonsList = Array.prototype.slice.call(buttons);
buttonsList.forEach(button => {
    button.addEventListener("click", () => {
        const offset = button.dataset.carouselButton === "next" ? 1 : -1
        const slides = button
            .closest("[data-carousel]")
            .querySelector("[data-slides]")

        const activeSlide = slides.querySelector("[data-active]")
        let newIndex = [...slides.children].indexOf(activeSlide) + offset

        if (newIndex < 0) newIndex = slides.children.length - 1
        if (newIndex >= slides.children.length) newIndex = 0

        slides.children[newIndex].dataset.active = true
        delete activeSlide.dataset.active
    })
})

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

I'm curious about what exactly happens when the NextJS Link component is triggered and how we can effectively capture and respond

As I was developing a simple navbar that uses a JSON data to dynamically generate its links, I encountered the need to visually persist the active link/route. To achieve this, I experimented with two different implementations: Initial approach: In the Me ...

What is the best way to include an arrow in a dropdown menu?

I've been working on restyling a Select box and I want to add a CSS arrow that rotates as the Select box expands. However, I'm struggling to align the arrow properly with the Select box. I've tried using code from the internet, but it hasn&a ...

Understanding the distinction among servlet responses in JavaScript?

I have a situation on my website where I am utilizing ajax to send information to a java servlet and then using the following javascript code to read the response: $.ajax({ url : 'myfirstservlet', async: false ...

Tips for effectively refining an Angular model (array) without compromising its integrity

I am currently working with a model for my view. This model consists of an array of objects: var arr = { "12345qwery": { prop1: "value", prop2: "value" } } // consisting of 500 items When filtering this array today, I use the following method: arr = $ ...

Looking to silence the audio completely or just mute it for mobile Android Chrome and Safari on iOS?

I am struggling to set the audio tag volume to zero or mute it using jQuery. The muted property works on desktop Chrome but not on Android Chrome. Here's a snippet of my code: song = document.getElementById('audio'); song.volume = 0.0; I h ...

Instructions on making one script activate another [jQuery] for resizing and enlarging a search box

Hi there, I'm facing a small dilemma and would appreciate some guidance. I've been working on creating a menu bar that mimics the functionality of apple.com (where the search bar expands when clicked to show options). Currently, I have a script ...

Utilize Backbone.js to organize and structure JSON data by populating it into nested collections and models within

I am new to Backbone.js and struggling with a complex problem. I need to save a form with infinite fields, some of which also have infinite options. My concern is that I started with a JSON response instead of building the models/collections first. Here&ap ...

Having an issue with collapsible feature when only one item is opened in AngularJS

I'm working on customizing a collapsible feature in my app. Instead of using the AngularJS UI Bootstrap accordion plugin, I opted to use transition.js and collapse.js from Bootstrap for a simpler design. My goal is to have 2 links next to each other w ...

Adjusting the width of an IFrame using CSS and JavaScript

I'm trying to adjust the width of my IFrame based on the size of the browser window. However, my current code is not producing the desired outcome even after refreshing the page. Can anyone pinpoint where I am going wrong? Here is the HTML snippet: ...

Captivating captions for captivating visuals. Pictures don't conform to a linear arrangement

As someone who is new to website creation, I am currently working on adding a CSS effect where a popup-text appears when an image is hovered over. I want to create a row of images for the popups by using an unordered list. However, I'm facing a proble ...

Can you pass a specific function as a parameter in express.post()?

I have a snippet of code that is functioning correctly. I am wondering if it is possible to pass a pre-defined function as a parameter within express.post(). const exs = require('express'); const exs_r = exs.Router(); router.post('/click&a ...

How can I prevent my JSON object from serializing .NET nulls as "null" for object members?

I am currently utilizing WebMethods to retrieve an array of a custom class. When this array is returned from a Jquery .ajax call, it gets serialized into a JSON object that can be utilized with Javascript in my ASP.NET application. The issue I am facing is ...

Stopping a jQuery AJAX request when the user switches to a different page

A method has been defined for sending a jQuery AJAX request as shown below: sendAjaxRequest(URL, data) { return $.ajax({ type : 'POST', url : URL, crossDomain : true, data : JSON.stringif ...

Ways to obtain the latitudes and longitudes for various routes between a starting point and a destination

At the moment, I am successfully retrieving all the latitude and longitude coordinates from the source to destination location. However, I am only able to obtain 1 path using this method. Now, I would like to have the ability to choose a specific route p ...

How is the rendering of a confirm/alert decided?

While browsing, I stumbled upon this intriguing query related to alerts and confirm dialogs, such as the one generated by alert('Hello World!'). My quest was to find a method to modify the text on the 'ok' and 'cancel' buttons ...

Connecting Angular and Socket.IO for Server-to-Server Communication

Can a simple socket.io connection be established between a client server running on Gulp and another server running on Node? .--------. .----------. .----------. |SERVER A| | | | SERVER B | | (Gulp) | | CLIEN ...

Can someone guide me on running a JavaScript code in Python with the help of Selenium?

My attempt to extract information using Selenium involved the following code: from selenium import webdriver # $ pip install selenium from selenium.webdriver.chrome.options import Options path = 'C:/Users/Жираслан/Downloads/chromedriver_win3 ...

`A problem with HTML element display in Internet Explorer versions 8 and 9 involving <p> and <h2> tags`

While working on my website, I encountered an issue with the way text is being rendered in <p> and <h2>. The footer of my site has three columns, but for some reason the middle column is displaying its <p> text within the <h2> text ...

Repainting can be an issue if the child element has not been transformed

My parent map has a large number of children pins, and I am experiencing significant slowdown while panning the map due to continuous repainting. Strangely, this issue is resolved when tapping on a child's pin and transforming the thumbnail inside it. ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...