JavaScript Slider for Color Selection

In my slider, I have added a .images class along with buttons for previous and next.

To set the colors, I have used JavaScript to define an array like this:

let colors = ['red', 'green',];

Currently, clicking the next-button displays the red color. This is done using the following function:

function nextSlide() {
  container.style.backgroundColor = colors[0];

I am looking to achieve a functionality where clicking the next button always displays the next color from the defined array. On the other hand, when the previous-button is clicked, the slider should show the previous color in the array.

You can see the complete source code below:

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

let colors = ['red', 'blue',];

nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);

function nextSlide() {
  container.style.backgroundColor = colors[0];
}

function prevSlide() {
  container.style.backgroundColor = colors[1];
}
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: lightblue;
}
.images {
  background-color: #4047c9;
  flex: 0 0 80%;
  min-height: 70vh;
  border-radius: 10px;
  position: relative;
}
.btn {
  display: inline-block;
  background: white;
  color: black;
  padding: 10px;
  border: none;
  cursor: pointer;
}
.prevBtn {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.nextBtn {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translate(50%, -50%);
  -webkit-transform: translate(50%, -50%);
  -moz-transform: translate(50%, -50%);
  -ms-transform: translate(50%, -50%);
}

.btn:active {
  background-color: grey;
  color: white;
}

.btn:hover {
  background-color: grey;
  color: white;
}
<div class="images">
  <button type="button" class="btn prevBtn">Prev Button</button>
  <button type="button" class="btn nextBtn">Next Button</button>
</div>

Answer №1

To achieve a looping effect where clicking on the last slide takes you to the first slide, and left-clicking on the first slide takes you to the last slide, you can utilize the modulus trick.

slideslength + currentslidenumber + directions %(modulus) slidelength

Here is an illustration of this concept:

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

let colors = ['red', 'green', 'blue',];
let currentSlide = 0;

function updateSlide(direction) {
  currentSlide = 
    (colors.length + currentSlide + direction)
    % colors.length;
  container.style.backgroundColor = colors[currentSlide];
}

updateSlide(0);

nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);

function nextSlide() {
  updateSlide(+1);
}

function prevSlide() {
  updateSlide(-1);
}
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: lightblue;
}

.images {
  background-color: #4047c9;
  flex: 0 0 80%;
  min-height: 70vh;
  border-radius: 10px;
  position: relative;
}

.btn {
  display: inline-block;
  background: white;
  color: black;
  padding: 10px;
  border: none;
  cursor: pointer;
}

.prevBtn {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translate(-50%, -50%);
}

.nextBtn {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translate(50%, -50%);
}

.btn:active {
  background-color: grey;
  color: white;
}

.btn:hover {
  background-color: grey;
  color: white;
}
<div class="images">
    <button type="button" class="btn prevBtn">Prev Btn</button>
    <button type="button" class="btn nextBtn">Next Btn</button>
  </div>

Answer №2

const nextButton = document.querySelector('.nextButton');
const previousButton = document.querySelector('.previousButton');
const imageContainer = document.querySelector('.imageGallery');

let imageColors = ['red', 'blue',];

let currentIndex = 0;

nextButton.addEventListener('click', showNextSlide);
previousButton.addEventListener('click', showPreviousSlide);

function showNextSlide() {
  imageContainer.style.backgroundColor = imageColors[currentIndex];
  if(currentIndex <= imageColors.length){
    currentIndex++;
  }else{
    currentIndex = 0;
  }
}

function showPreviousSlide() {
  imageContainer.style.backgroundColor = imageColors[currentIndex];
  if(currentIndex <= imageColors.length){
    currentIndex--;
  }else{
    currentIndex = 0;
  }
}

<div class="imageGallery">
    <button type="button" class="btn prevBtn">Show Previous Slide</button>
    <button type="button" class="btn nextBtn">Show Next Slide</button>
  </div>

Answer №3

To create a counter that increments or decrements on each function call, ensuring it stays within the bounds of the array length and uses the counter as an index to assign colors from a color array:

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

let colors = ['purple', 'orange', 'pink', 'teal'];

nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
var i=0;

function nextSlide() {
if(i>=colors.length-1)
i=0;
if(i<0)
i=colors.length-1;
  container.style.backgroundColor = colors[i++];

}

function prevSlide() {
if(i>=colors.length-1)
i=0;
if(i<0)
i=colors.length-1;
  container.style.backgroundColor = colors[i--];
}
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: lightcoral;
}

.images {
  background-color: #22a7f0;
  flex: 0 0 80%;
  min-height: 70vh;
  border-radius: 10px;
  position: relative;
}

.btn {
  display: inline-block;
  background: white;
  color: black;
  padding: 10px;
  border: none;
  cursor: pointer;
}

.prevBtn {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translate(-50%, -50%);
}

.nextBtn {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translate(50%, -50%);
}

.btn:active {
  background-color: purple;
  color: white;
}

.btn:hover {
  background-color: purple;
  color: white;
}
<div class="images">
    <button type="button" class="btn prevBtn">Previous</button>
    <button type="button" class="btn nextBtn">Next</button>
  </div>

Answer №4

Great job! You're almost there, all you need to do is add an index variable to keep track of the current position in your color array:

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

let colors = ['red', 'blue', 'yellow', 'green'];
let index = 0;
let length = colors.length;

nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);

function changeColor() {
  container.style.backgroundColor = colors[index];
}

function nextSlide() {
 if(index == length - 1){
   index = 0;
 }else{
   index++;
 }
 changeColor();
}

function prevSlide() {
  if(index == 0){
    index = length - 1;
  }else {
    index--;
  }
  changeColor();
}
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: lightblue;
}

.images {
  background-color: #4047c9;
  flex: 0 0 80%;
  min-height: 70vh;
  border-radius: 10px;
  position: relative;
}

.btn {
  display: inline-block;
  background: white;
  color: black;
  padding: 10px;
  border: none;
  cursor: pointer;
}

.prevBtn {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translate(-50%, -50%);
}

.nextBtn {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translate(50%, -50%);
}

.btn:active {
  background-color: grey;
  color: white;
}

.btn:hover {
  background-color: grey;
  color: white;
}
<div class="images">
    <button type="button" class="btn prevBtn">Prev Btn</button>
    <button type="button" class="btn nextBtn">Next Btn</button>
  </div>

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

After applying sorting, jqGrid displays an empty space below the final row

Having an unusual problem with sorting in the jqGrid. When I sort in descending order, there is extra space below the last row, but when I sort in ascending order, the table ends abruptly at the bottom without allowing any further scrolling. I have includ ...

Jest tests are failing because React is not defined

I am attempting to implement unit tests using Jest and React Testing Library in my code. However, I have encountered an issue where the tests are failing due to the React variable being undefined. Below is my configuration: const { pathsToModuleNameMapper ...

Angular filter within a nested ng-repeat loop

I've encountered an issue with nested filtering in Angular, where two filters are dependent on each other. What I'm trying to achieve is the following: <div ng-repeat="g in groups | filter:groupFilter"> ... <tr ng-repeat="c in g.co ...

What could be the reason for the Mongoose findAll function causing a 500 error to occur?

My model / Schema has a working create method, but the "all" method is causing a 500 error. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var DiSchema = new mongoose.Schema({ name: { type: String, lowercase: true , require ...

Error: The last line is missing a trailing comma

I'm struggling to understand why my tslint insists on having a trailing comma at the end of the last line in the objects. Is there a way to configure the ignore rule for the last line of objects? Appreciate any help! For example: settings = { ...

Efficiently repositioning Kendo Mobile Buttongroup to a new row as needed

In my current project, there is a specific requirement to display three button groups in a row. If there are more than three buttons, they should move to the next row dynamically as the data will be fetched from the server. For reference, below is a sampl ...

How can I customize the variables in Webpack for Sass and Foundation?

Currently, I am in the process of using webpack to manage all of my project assets. In my app.js file, I am loading and concatenating my assets with the help of ExtractTextPlugin: import 'foundation-sites/scss/normalize.scss'; import 'foun ...

Struggling with Angular 8: Attempting to utilize form data for string formatting in a service, but encountering persistent page reloading and failure to reassign variables from form values

My goal is to extract the zip code from a form, create a URL based on that zip code, make an API call using that URL, and then display the JSON data on the screen. I have successfully generated the URL and retrieved the necessary data. However, I am strug ...

Communication between a directive controller and a service via an HTTP call

I'm currently developing an Angular directive that loads a Highchart.js area graph by passing some variables to it. Here's how I am using the directive: <andamento-fondo-area-chart color="#3FAE2A" url="../data.json"></andamento-fondo-a ...

What is the reason behind Internet Explorer 11 not supporting conditional comments in HTML? Has this feature been dropped?

I'm having an issue trying to show different content on various web browsers. When using Internet Explorer 11 and Google Chrome 39, the message displayed is "Not Internet Explorer" instead of the expected result. Is there a problem with my code? It&ap ...

Personalized Pinterest button to link to a custom URL (Text Link, Image, or Both)

I've been searching for a solution without success. I'm looking to customize the image for my Pinterest (Pin It) button and pin a specific image by URL, not just the current page. Here is the custom link I created: <a href="http://pinterest. ...

Use JavaScript regex to replace a string only if its length exceeds a certain specified limit

My current approach involves using JavaScript regex to insert an HTML markup for all identified URLs: var exp = /(((|www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|&bso ...

Updating chart.js data seems to be presenting some challenges

Need help fetching data with an AJAX request to update chart.js. The AJAX request is working fine, but the response doesn't update the chart. This is how I fetch the data: <script type="text/javascript"> $(document).ready(function(){ $("#da ...

a dedicated TypeScript interface for a particular JSON schema

I am pondering, how can I generate a TypeScript interface for JSON data like this: "Cities": { "NY": ["New York", [8000, 134]], "LA": ["Los Angeles", [4000, 97]], } I'm uncertain about how to handle these nested arrays and u ...

Using an if-else statement within a Vue event listener

Can this task be achieved using Vue: <button @click="(true) ? funcA : FuncB"> Click </button> In this scenario, the event is a click, however it could also involve keypress, keydown, input or any other events documented in vuejs. If ...

Issues with NodeJs Express routes execution

After testing, I found that only the default route "/" is working in my code. Many similar issues involve routers being mounted to paths like "/auth" or "/user". Even when I tested the default router mounted to "/", it still isn't functioning properly ...

Log into your account by choosing a button using Selenium with Python

While attempting to access my account via this specific link on the Market Watch webpage using Python and Selenium, I encountered a roadblock. Despite successfully selecting the "Sign In" button, no action is triggered, preventing me from entering the desi ...

Choose2 incorporate on change

I have a Laravel project where I am using the vuexy theme. I've been trying to add an onchange event to my select2 input, but so far I haven't had any success. Here is my select2 input: <div class="col-12 mb-2"> <label class ...

Choosing the Offspring: Deliberating on Multiple Children with Identical Names in Selenium

Just starting out with Selenium and web development in general, I've encountered a problem with locating an element using XPath. selenium.common.exceptions.NoSuchElementException I've been trying to troubleshoot for a while now, but haven' ...

What steps should be taken to transform this Jquery Ajax code into Pure Javascript Fetch?

I am looking to convert this Jquery Ajax snippet to Fetch using Pure Javascript. Can you provide assistance? I attempted this previously, but my code did not function properly. I even posted a question about it here. That is why I am hoping for your help ...