changing the elements' classes by using a carousel

Having trouble with a custom carousel and unable to use the standard Bootstrap carousel.

This is how my code is structured:

Images:

 <img src="1.img"/>
 <img src="2.img"/>
 <img src="3.img"/>

Prev / Next buttons:

 <div class="left"></div> left button
 <div class="right"></div> right button

These buttons navigate through elements in the "ol" table.

Ol Table:

 <ol>
      <li>Circle 1</li>
      <li class="active">Circle 2</li>
      <li>Circle 3</li>
 </ol> 

Clicking on a button loads data corresponding to that element, marking it as active.

The issue lies with the Prev / Next buttons operation. Given an HTML "ol" with three elements, I need them to cycle properly when clicked.

Starting from the second element with an active class, I aim to use jQuery prev() and next() functions in a for loop to ensure correct navigation behavior.

Current logic on click of "next" (and vice versa with "prev") buttons:

 $("li.active").next().addClass("active");
 $("li.active").prev().removeClass("active");

Encountering two problems: 1) Selection issues between elements when clicking to navigate forward. 2) Incorrect element selection when navigating backwards. A for loop seems necessary to address these challenges. Can anyone assist with this? Thank you.

Answer â„–1

Below is the code snippet for the next button functionality:

$(".next").on("click", function(){
  moveToNext();
});//.next click

function moveToNext()
{
  var curIndex = $("ol li.active").index();
  var totalSlides = $("ol li").length;
  var nextIndex = curIndex + 1;

  if( nextIndex >= totalSlides )
  {
    nextIndex = 0;
  }//if

  $("ol li.active").removeClass("active");
  $("ol li").eq( nextIndex ).addClass("active").trigger("click");

}//moveToNext();

You can use a similar approach to implement functionality for the previous button as well.

Answer â„–2

A Simple Vanilla JavaScript Approach with Previous and Next Functionality

var nextButton = document.querySelector('#next');
var previousButton = document.querySelector('#previous');
var imageItems = document.querySelectorAll('.slider img');
var circles = document.querySelectorAll('.slider ol li');
var counter = 0;

if (nextButton) {
  nextButton.addEventListener('click', displayNextImage, false);
  previousButton.addEventListener('click', displayPreviousImage, false);
}

for (var i = 0; i < circles.length; i++) {
  var circleElement = circles[i];
  circleElement.addEventListener('click', function() {

    for (var j = 0; j < imageItems.length; j++) {
      if (imageItems[j].classList.contains('active')) {
        imageItems[j].classList.remove('active');
      }
      if (circles[j].classList.contains('active')) {
        circles[j].classList.remove('active');
      }
    }

    imageItems[this.dataset.count].classList.add('active');
    circles[this.dataset.count].classList.add('active');
    counter = this.dataset.count;
  });
}

function displayNextImage() {
  for (var i = 0; i < imageItems.length; i++) {
    if (imageItems[i].classList.contains('active')) {
      imageItems[i].classList.remove('active');
    }
    if (circles[i].classList.contains('active')) {
      circles[i].classList.remove('active');
    }
  }
  if (counter === imageItems.length - 1) {
    counter = 0;
    imageItems[counter].classList.add('active');
    circles[counter].classList.add('active');
  } else {
    counter++;
    imageItems[counter].classList.add('active');
    circles[counter].classList.add('active');
  }

}

function displayPreviousImage() {
  for (var i = 0; i < imageItems.length; i++) {
    if (imageItems[i].classList.contains('active')) {
      imageItems[i].classList.remove('active');
    }
    if (circles[i].classList.contains('active')) {
      circles[i].classList.remove('active');
    }
  }
  if (counter === 0) {
    counter = imageItems.length - 1;
    imageItems[counter].classList.add('active');
    circles[counter].classList.add('active');
  } else {
    counter--;
    imageItems[counter].classList.add('active');
    circles[counter].classList.add('active');
  }

}
img {
  width: 120px;
  height: 120px;
}
img.active {
  background: #DDD;
}
li.active {
  color: #000;
  background: #ddd;
}
ol li {
  background: #fff;
  border: 1px solid #DDD;
  cursor: pointer;
  padding: 3px;
  display: inline-block;
}
<div class="slider">

  <img class='active' src="" />
  <img src="" />
  <img src="" />

  <ol>
    <li data-count='0' class="active">Circle 1</li>
    <li data-count='1'>Circle 2</li>
    <li data-count='2'>Circle 3</li>
  </ol>
</div>

<button id="previous">Previous</button>

<button id="next">Next</button>

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

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

What is the reason behind genNewColor function's malfunction?

I'm having trouble with this code that is supposed to generate a random color. The CSS formatting works perfectly, but I suspect there might be an issue with the function itself. When I try to run the code, it doesn't produce any error messages â ...

Experiencing odd behavior with my Dash App when using CSS grid on it

Seeking assistance with my coding issue, I believe sharing my code from Github would be the most efficient way to address it. An exclusive branch named css_problem_branch has been created to showcase the problem at hand. To access the Github repository, p ...

Encountering a npm script error while running on a Windows operating

While using webpack to build my application, I encountered the following error message in the command prompt: [email protected] dev D:\Myprograms\java script\forkify webpack --mode development The error mentioned: Insufficient num ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

Ways to showcase tooltip text for an unordered list item?

When creating an unordered list, each element's text corresponds to a chapter name. I also want to include the description of each chapter as tooltip text. The Javascript code I currently have for generating a list item is: var list_item = document.c ...

Angular and JavaScript: Today is Monday and the date is exactly one week old

I am currently working on an Angular application that is connected to a REST API. In order to minimize the number of requests made, I have implemented a method to store all data in the local storage. .factory('$localstorage', ['$window&apos ...

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

improve your AJAX implementation in Django

Recently, I implemented some AJAX functionality in a Django application that I have been developing. Coming from a background in Ruby on Rails, I haven't had much experience with pure JavaScript. So, inspired by Rails' partials, I came up with ...

Looking to center the numbers in my ordered list within a border box - any tips on how to achieve this?

I'm attempting to create a numbered order list with a circular border around it. The goal is to have the number of the list item centered within the circular border and the entire circle centered within the paragraph. Currently, both the number and th ...

Placing JavaScript at the bottom of the page, sourced from a Partial Page

I'm trying to display JavaScript code from a Razor Partial Page at the bottom of a (layout) Page. In a similar discussion on Stack Overflow about Including JavaScript at bottom of page, from Partial Views, it was suggested by user Becuzz that using a ...

When you click, a new webpage opens within my website, similar to the feature on Facebook

When using Facebook on mobile, clicking on a link to a person's website opens the website in front of the Facebook page. However, when users press the X in the top left corner, it deletes the webpage but keeps Facebook open. On my desktop computer, I ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Is there a way to automatically remove files from the "dist" directory when deleting the prototype from the "src" folder?

I am new to build systems and seeking assistance with the following question. Here is the structure of my boilerplate: /src (working folder) ___/templates(jade files) ___/scss ___/scripts /dist (compiled files) ___/css ___/js ___.html files In the te ...

Using Python to interact with website dropdown menus without relying on Selenium

Is there a Python library available that can assist me in opening a web page, selecting options from drop-down lists, and performing clicks without relying on Selenium? ...

Protractor: Unable to reach variables within closure set in the parent function

I have a code snippet in one of my JS files that looks like this: // test/lib/UserHelper.js 'use strict'; var Firebase = require('firebase'); exports.createUser = function (email, password) { browser.executeAsyncScript(function (do ...

The system is unable to retrieve the value of the property which is set as null

I'm trying to figure out how to store the input value of name_enter into the variable userName. However, every time I attempt this, I encounter the following console error: Uncaught TypeError: Cannot read property 'value' of null function ...

React Bootstrap encountered rendering issues

Recently, I decided to delve into the world of React Bootstrap and started my learning journey. To get started, I followed some tutorials on <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="vi ...

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

Tips for creating a concise summary of written content

I am interested in creating an AI-powered summary generator for text input within a textarea element. Below is the HTML code snippet I have been working with: <textarea id="summary">Enter your text here</textarea> If you hav ...