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

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

What is the best way to sort a combination of numbers and text strings?

Within my table, I have column names enclosed in <th> tags and only numerical values inside <td> tags. When the user clicks on a <th> tag, the sorting algorithm organizes the values in ascending or descending order. .sortElements(function ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Which Web Browsers Support Canvas and HTML5?

Currently working on a project that involves using the HTML5 Canvas element. I am curious about which major browsers (including specific versions) actually support the Canvas tag. I am not interested in hearing about IE. In this tutorial Drawing shapes - M ...

The positioning of the <thead> element does not seem to be functioning properly

I attempted to create a background for the header (thead) using a pseudo element (:after) because I wanted the background to span from one edge to another edge (including both left and right side padding). However, thead is not taking a relative position a ...

Using Javascript to organize an array of objects based on a specific condition

Having an array of objects structured as follows: obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3}, {'name': 'Sam', ...

Use regular expressions to locate all closing HTML tags and all opening HTML tags individually

My JavaScript function is currently filtering strings by removing all HTML tags. However, I have now realized that I need to perform two separate operations: first, replacing all closing tags with <br>, and then removing all opening tags. return Str ...

Ways to create space around Navbar MUI for a more balanced design

Currently, I am working on designing a navigation bar using MUI. My goal is to create a navbar with some space on both sides similar to the one seen on If you take a look at Stackoverflow's navbar, you will notice that it also has space on either sid ...

The battle of line-height versus padding for achieving vertical centering with one-lined text

One-lined text can be vertically centered using either the line-height property or by adding padding-top and padding-bottom. What are the advantages and disadvantages of each method? body { font-size: 12px; font-family: ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

Navigating AngularJS with multiple external files and folders

Recently dove into Angular and hit a roadblock with routing. I followed the setup instructions, but for some reason it's not functioning as expected. index.html: <!DOCTYPE html> <html lang="en> <head> <meta charset="utf-8> ...

Transforming the jQuery tooltip to be shown in a column layout

Hello, I am currently using the displayTag library to showcase some tables. My goal is to include a tooltip on each display:column element by utilizing jQuery. Below is the code snippet in question: <c:set var="titleName"><wp:i18n key="FILENAME" ...

The requested Javascript function could not be found

I have the following JavaScript function that creates a button element with a click event attached to it. function Button(id, url, blockMsg){ var id = id; var url = url; var blockMsg = blockMsg; var message; this.getId = function(){ return id; }; th ...

How to reference an object from an external file in TypeScript using Ionic 2 and Angular 2

I am currently developing a mobile application with Ionic2 and have integrated a simple online payment service called Paystack for processing payments. The way it operates is by adding a js file to your webpage and then invoking a function. <script> ...

Get the JSON file from Firebase storage

My query boils down to this: Within my vue.js application, I am uploading a json file to a firebase storage bucket. However, when attempting to download the file for use within the app, I encounter an "Uncaught (in promise) undefined" error. The goal is t ...

Left-aligned arrow for Material UI select dropdown

Just starting out with material ui and I'm trying to grasp a few concepts. I have a basic select component but encountering two issues. Firstly, I'd like to move the arrow icon of the select to the left side instead of the right. Additionally, ...

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

The external hyperlink is not functional in Firefox and Chrome browsers, but it operates properly in Internet Explorer 9

For security reasons, it seems that embedding an external link for live scoring from itftennis.com on our website is blocked. If you try to click on the jsfiddle LIVE SCORING link, it will open a page with an error. However, if you click on the address ba ...

Error message: The call stack size has surpassed the limit, resulting in a RangeError. This issue is

I currently have a dynamic unordered list within my HTML file. Upon loading the page, certain list items are automatically added. The original format of the list is displayed as follows: <ul class="ui-front"> <li><div>1</div& ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...