Creating a carousel of cards using JavaScript, CSS, and HTML

Here is a visual reference of what I'm attempting to achieve: https://i.stack.imgur.com/EoQYV.png

I've been working on creating a carousel with cards, but I'm struggling to synchronize the button indicators with card advancement when clicked, as illustrated in the image. Can someone assist me in figuring out how to achieve this synchronization between the indicators and card progression upon clicking?

let targeta = document.querySelectorAll('.card');
let puntos = document.querySelectorAll('.secciones .punto');

for (i = 0; i < targeta.length; i++) {
  puntos[i].addEventListener('click', function(evento) {
    for (i = 0; i < puntos.length; i++) {
      puntos[i].classList.remove('activo');
    }
    clase_activo(evento);
  });

  targeta[i].addEventListener('click', function(evento) {
    for (i = 0; i < puntos.length; i++) {
      targeta[i].classList.remove('activo');
    }
    clase_activo(evento);
  });
}

function clase_activo(evento) {
  if (evento.target.classList.contains('activo')) {
    evento.target.classList.remove('activo');
  } else {
    evento.target.classList.add('activo');
  }
}
.product-list {
  background: #dfe6e9;
  padding: 3em;
}

.product-list .card {
  background: white;
  border-radius: 10px;
  padding: 1em;
  box-shadow: 0px 10px 5px #b2bec3;
  text-align: center;
  font-family: 'SpaceGrotesk-medium';
}

.card {
  height: 300px;
}

.product-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-column-gap: 20px;
  grid-row-gap: 40px;
}

.secciones {
  display: flex;
  align-items: center;
  /*      background: #fb6969;*/
  justify-content: center;
}

.punto {
  background: #b4f028;
  /* #fb9769; */
  height: 10px;
  width: 30px;
  border-radius: 5px;
  padding: 0 5px;
  margin: 0 2px;
}

.punto.activo {
  background: #f07e28;
  /* #fb9769; */
}

.card.activo {
  background: #f07e28;
}
<section class="product-list">
  <h1>productos</h1>
  <div class="product-container">

    <div class="card 1 activo">
    </div>

    <div class="card 2 ">
    </div>

    <div class="card 3 ">
    </div>

    <div class="card 4 ">
    </div>

  </div>
  <div class="secciones">
    <div class="punto  activo"></div>
    <div class="punto "></div>
    <div class="punto "></div>
    <div class="punto "></div>
  </div>
</section>

Answer №1

In order to enhance user interaction, I utilized a loop to assign click events to both the cards and dots displayed on the webpage. Whenever a card or dot is clicked, the active class gets removed from all other cards and dots, and then it is added to the clicked item along with its corresponding pair.

// Accessing all cards and dots
let cards = document.querySelectorAll('.card');
let dots = document.querySelectorAll('.secciones .punto');

// Iterating through each card and dot
for (let i = 0; i < cards.length; i++) {
    // Adding click event to each card
    cards[i].addEventListener('click', function() {
        for (let j = 0; j < cards.length; j++) {
            // Removing active class from all cards
            cards[j].classList.remove('activo');
            dots[j].classList.remove('activo');
        }
        // Adding active class to the clicked card
        this.classList.add('activo');
        dots[i].classList.add('activo');
    });

    // Adding click event to each dot
    dots[i].addEventListener('click', function() {
        for (let j = 0; j < cards.length; j++) {
            // Removing active class from all cards
            cards[j].classList.remove('activo');
            dots[j].classList.remove('activo');
        }
        // Adding active class to the corresponding card
        cards[i].classList.add('activo');
        this.classList.add('activo');
    });
}

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

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

The number input is not compatible with JavaScript/jQuery validation

While working on input field validation using javascript/jQuery code, I encountered an issue where the code worked fine with input type text but did not support input type number. Specifically, the 'number' type input did not work at all in FireF ...

struggling to develop a sophisticated 'shopping cart organization' program

I am in the process of creating a database for video spots, where users can view and modify a list of spots. I am currently working on implementing a cart system that automatically stores checked spot IDs as cookies, allowing users to browse multiple pages ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

Checking to see if there are a minimum of two checkboxes selected before inputting the data into the database

I am currently using a combination of HTML, PHP, JavaScript, MySQL, and Wampserver. In my project, I have implemented 3 checkboxes where the user can choose a maximum of two options. Once selected, these choices are then inserted into the database. Initi ...

How can I create multiple divs that look alike?

I've taken on the challenge of developing our own interpretation of Conway's "Game of Life" for a project. To represent my 20x20 grid, I decided to create nested divs - the whole grid is one div, each row is a div, and every cell within that is a ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

JavaScript node_modules import issue

I've been grappling with this issue for quite some time now. The problem lies in the malfunctioning of imports, and I cannot seem to pinpoint the exact reason behind it. Let me provide you with a few instances: In my index.html file, which is complet ...

How can I modify the content within a scoped `<style>` tag in Vue?

Is there a way to dynamically change the contents of a <style> block in my Vue component using Vue variables? Many commonly suggested solutions involve inline styles or accessing the .style property with JavaScript. However, I am looking for a metho ...

Are there any universal methods for enlarging the size of a checkbox without altering the HTML structure?

Is it possible to adjust the size of a <input type="checkbox"> in a way that works across all browsers without changing the HTML markup? I attempted to modify the height and width using CSS, but encountered issues such as pixelation in Firefox and o ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

I am encountering a problem while attempting to fetch information from Firestore through the Firebase JS SDK

My current challenge revolves around retrieving data from Firestore using the Firebase JS SDK. A specific error message persists: An unexpected issue arises: TypeError: firebase_firestore__WEBPACK_IMPORTED_MODULE_3__.getDoc(...).data is not a function I ...

Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

The height and alignment of the <a> tag and <p> element vary within a flex container

Currently, I am in the process of constructing a bottom navigation bar for a blog page. This navigation bar will allow users to easily navigate between the last blog entry, the main blog home/index, and the upcoming post. However, when the user reaches the ...

The table's pagination displays above, thanks to Tailwindcss

I'm facing an issue where the pagination is showing up above the table, but I was expecting it to be displayed after the table. It would be ideal if the pagination appeared right after the table when adding multiple rows. Check this link for more inf ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

A guide on configuring Flexbox to consistently display three columns

For the website I'm working on, I've utilized Flexbox to properly align the items. Within the div .main, I have organized the content in separate divs. These are the CSS properties that I've applied: .main{ margin: 0 auto; /*max-height: ...