Is there a way to have these slides repeat automatically?

After spend some time working on this, I've hit a roadblock.

I managed to create a div slider with navigation arrows where each slide has a minimum width of 80px.

The code functions correctly, except that when I reach the last item and try to navigate further, it stops. I want the slider to loop infinitely instead of stopping at the last item.

let buttonLeft = document.getElementById('slide_left')
                let buttonRight = document.getElementById('slide_right')

                buttonLeft.addEventListener('click', function() {
                    document.getElementById('slider').scrollLeft -= 90
                })

                buttonRight.addEventListener('click', function() {
                    document.getElementById('slider').scrollLeft += 90
                })
body{
                        background-color: #555;
                        height: 100vh;
                        display: grid;
                        align-items: center;
                        justify-items: center;
                        font-family: 'Helvetica';
                    }

                    div#slide_wrapper{
                        width: 440px;
                        display: flex;
                        justify-content: space-between;
                        height: fit-content;
                    }

                    div#slider{
                        width: 350px;
                        display: flex;
                        height: fit-content;
                        flex-wrap: nowrap;
                        overflow: hidden;
                    }
                    
                    <!-- More CSS styles -->

                
<div id="slide_wrapper">
                    <button id="slide_left" class="slide_arrow">&#10094;</button>
                    <div id="slider">
                        <div class="thumbnail active">1</div>
                        <div class="thumbnail">2</div>
                        <div class="thumbnail">3</div>
                        <div class="thumbnail">4</div>
                        <div class="thumbnail">5</div>
                        <div class="thumbnail">6</div>
                        <div class="thumbnail">7</div>
                        <div class="thumbnail">8</div>
                    </div>
                    <button id="slide_right" class="slide_arrow">&#10095;</button>
                </div>

Answer №1

Great job on the slider implementation! There are multiple approaches to achieve the desired functionality. In my view, the most straightforward solution involves using if conditions and a counter variable. Reset the counter to 0 once the limit of thumbnails is reached.

Update

In response to your query, "How about doing the same for the left arrow.", I made the following additions within the if condition block: if (0 == slideCount) {:

    slideCount = thumbnail.length // set the slideCounter to maximum
    document.getElementById('slider').scrollLeft = slideCount * 90 // calculate the scroll distance
    slideCount--; // decrease slidecount
    setActive();  // set the red border on the current slide

const buttonLeft = document.getElementById('slide_left')
const  buttonRight = document.getElementById('slide_right')
const thumbnail = document.querySelectorAll(".thumbnail");
let slideCount = 0;
setActive();

buttonLeft.addEventListener('click', function() {
  if (0 == slideCount) {
    slideCount = thumbnail.length
    document.getElementById('slider').scrollLeft = slideCount * 90
    slideCount--;
    setActive();    
    return;
  }
  slideCount--;
  document.getElementById('slider').scrollLeft -= 90  
  setActive();
})

buttonRight.addEventListener('click', function() {
  slideCount++;
  if ( 8  ==  slideCount) {    
    document.getElementById('slider').scrollLeft = 0
    slideCount = 0;
  } else {
    document.getElementById('slider').scrollLeft += 90  
  }    
  setActive();
})

function setActive() {  
  thumbnail.forEach(t => {
    t.classList.remove("active");
  })
  thumbnail[slideCount].classList.add("active")
}

function count() {
  console.log(slideCount);
}
body{
  background-color: #555;
  height: 100vh;
  display: grid;
  align-items: center;
  justify-items: center;
  font-family: 'Helvetica';
}
 /* CSS Styles */
<div id="slide_wrapper">
  <button id="slide_left" class="slide_arrow">&#10094;</button>
  <div id="slider">
    <div class="thumbnail active">1</div>
    <div class="thumbnail">2</div>
    <div class="thumbnail">3</div>
    <div class="thumbnail">4</div>
    <div class="thumbnail">5</div>
    <div class="thumbnail">6</div>
    <div class="thumbnail">7</div>
    <div class="thumbnail">8</div>
  </div>
  <button id="slide_right" class="slide_arrow">&#10095;</button>
</div>

Answer №2

To determine the width of the slider, simply compare it to the scroll left position using the following JavaScript:

 let buttonLeft = document.getElementById('slide_left')
let buttonRight = document.getElementById('slide_right')

buttonLeft.addEventListener('click', function() {
    document.getElementById('slider').scrollLeft -= 90
})

buttonRight.addEventListener('click', function() {

  const elem = document.getElementById('slider');
  
  const ElemWidth = elem.getClientRects()[0].width
 
 if(document.getElementById('slider').scrollLeft > ElemWidth ){
    document.getElementById('slider').scrollLeft = 0
 }else{
   document.getElementById('slider').scrollLeft += 90 
 }
  
   console.log(ElemWidth,  document.getElementById('slider').scrollLeft , document.getElementById('slider').scrollLeft > ElemWidth)
})

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

While iterating over the key with a variable in a loop, only one property is displayed consistently instead of four different

Currently, I am working on creating an address book using JavaScript. The problem I am facing is that the properties of my objects are not providing me with the necessary information. I need 4 different properties instead of 4 loops with the same property. ...

Customizing functions in JavaScript with constructor property

What is the best way to implement method overriding in JavaScript that is both effective and cross-browser compatible? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; ...

When activated, JavaScript is producing an undefined response

This is a function with the following designer code. I have made updates to include the latest answer. function OnClientLoBChecked(sender, args) { var ChkBoxLOB = document.getElementById("<%= cbFLoB.ClientID %>"); var ChkBoxDis = document ...

Developing a calendar with limited availability for selecting future dates and restricting the ability to choose past dates

I am currently working on creating a calendar in Vue.js that allows users to select dates only from the current day up to the next 30 days. Dates prior to the current date are disabled, as well as dates beyond the initial 30-day period. While I have exper ...

Breaking AngularJS into an array

I need help splitting my data stored in a single array into multiple arrays. Currently, I am using "|" as the separator to split them, but I want to store each split value in separate arrays. https://i.sstatic.net/wW5QV.png JavaScript: { $ ...

Sharing Variable Across Multiple Pages

I have successfully passed a variable from a link on my first page to the second page, but I am encountering difficulties when trying to pass that variable into the third page. How can I accomplish this? The First Page is an HTML Page <a href="SecondP ...

Having trouble resolving the BooksAPI in my code, can anyone help?

I've been trying to troubleshoot this problem, but I can't seem to find a solution. I'm working on a web application for book reading that allows users to organize books they have read, want to read, and are currently reading. On the search ...

How can I use vanilla JavaScript to retrieve all elements within the body tag while excluding a specific div and its descendants?

My goal is to identify all elements within the body tag, except for one specific element with a class of "hidden" and its children. Here is the variable that stores all elements in the body: allTagsInBody = document.body.getElementsByTagName('*&apos ...

Safari's compatibility issues with Next.js Images are preventing Flexbox from working properly

I'm trying to lay out Next.js Images using flex-wrap with a fixed height but variable width based on the image. I'm utilizing tailwind for this project. Everything is working perfectly on Google Chrome as expected. https://i.sstatic.net/KTTx9.j ...

Click on the social media icon to access the link

Recently, I created a social media icon list for my website but I'm struggling to figure out how to add clickable links to them. I attempted using the "a" tag, but it's not functioning as expected: <div class="leftside"> <ul class= ...

How can I programmatically trigger a change event for a dropdown in Vue.js?

I am looking to trigger a dropdown change event within a Vue.js method. <select id="idDropdown" v-model="Result.Value" v-on:change.prevent="changeSelection($event, 'somevalue')"> How can I call the above `cha ...

Revamp nested .map calls to utilize async/await pattern

Currently, I am working with a JSON file structured similarly to the example below: [ { "Item": "Item1", "ItemChild": [ { "Category": "Category1", ...

Can you explain the significance of these specific HTML attributes within the button tag?

While browsing the web, I stumbled upon this HTML snippet: <button class="button--standard" mat-button mat-flat-button [disabled]=true >Disabled State</button> The combination of attributes like mat-button mat-flat-button [disabled]=true is u ...

Navigating through elements within underscore.js templates

Can someone please help me out? I'm finding this task more difficult than it should be, so I must be overlooking something simple... I am working with a variable that is acting as an underscore template. Here is an example of the code snippet: var t ...

The issue with VS Code is that it is running the wrong file instead of

Whenever I try to run my Python file, it keeps opening the previous HTML file instead. Despite clicking "run" on my Python file in VS Code, the terminal is not executing (as it normally does), and instead VS Code continues to open the previously opened HT ...

Attempting to retrieve backend data through an API to be displayed on the frontend

After successfully sending form data from my React front end to the server using fetch, I am struggling to make this data accessible from the front end again. Despite being able to access and utilize the data within my API function on the server side, I&ap ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

Calling Ajax inside each iteration loop

I have encountered numerous posts discussing this topic, but the solutions I came across do not quite suit my needs. Some experts suggest changing the code structure, however, I am unsure of how to go about doing that. What I desire: 1) Retrieve a list ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...