Activate all chosen CSS circles

I'm currently working on creating a progress bar using CSS circles. The idea is that when you click on each circle in sequence (1, 2, 3), all three circles and the line connecting them will fill up with red color. If you then go back (3, 2, 1), the color should be removed.

HTML:

<div class="row well" id="rows">
        <ul id="progressbar" class="progressbar">
            <li class="cir danger">THOUGHFUL</li>
            <li class="cir">PASSION</li>
            <li class="cir">POWER OF DESIGN</li>
            <li class="cir">BUILDING RELATIONSHIPS</li>
            <li class="cir">ENHANCE HUMAN INTERATION</li>
        </ul>
    </div>

JS :

var header = document.getElementById("rows");
        var bar = document.getElementsByClassName("progressbar");
        var btns = header.getElementsByClassName("cir");
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click", function () {
                var danger = document.getElementsByClassName("danger");
                danger[0].className = danger[0].className.replace("danger", "");
                this.className += " danger";
            });
        }

Sample Img: https://i.sstatic.net/XxRi1.gif

In reference to the image above, if I click on circle 3, circles 1, 2, and 3 should turn red. Then, if I click on circle 2, circle 3 should turn white while circles 1 and 2 remain red. I tried implementing this using JS but encountered a classnotfound error.

Any assistance with this would be greatly appreciated.

Answer №1

Whenever a circle is clicked, extract its data-id and activate all circles with an equal or lower data-id.

let circles = document.querySelectorAll(".circle")
circles.forEach(el => {
   el.addEventListener("click", (e) => {
     let id = e.target.dataset.id
     circles.forEach(el2 => {
        if(el2.dataset.id <= id){
            el2.classList.add("active")
        }else{
            el2.classList.remove("active")
        }
     })   
   })
})
.circled{display:flex}
.circle{
   border-radius:50%;
   width:50px;
   height:50px;
   border: solid 2px #333;
   display:inline-flex;
   align-items:center;
   justify-content:center;
   position:relative;
   margin-left: 44px;
   cursor:pointer;
}

.circle:not(:first-of-type)::before{
   height: 2px;
   width: 50px;
   content:"";
   background-color: #333;
   position:absolute;
   left:-50px;
}

.circle.active{
   border-color: #f00;
}

.circle.active:not(:first-of-type)::before{
   background-color: #f00;
}
<div class="circles">
   <div class="circle active" data-id="1">1</div>
   <div class="circle" data-id="2">2</div>
   <div class="circle" data-id="3">3</div>
   <div class="circle" data-id="4">4</div>
   <div class="circle" data-id="5">5</div>
</div>

Answer №2

Feeling remorseful about this

var header = document.getElementById("rows");
var bar = document.getElementsByClassName("progressbar");
var btns = header.getElementsByClassName("cir");

Array.prototype.forEach.call(btns,function(btn){
    btn.addEventListener('click', function(e){
    adjustProgressBar(btn,e)
  })
});

function adjustProgressBar(btn,e){
    clearDangerSign();

  for( let btnToCheck of btns){
    btnToCheck.classList.add('danger');

    if (btnToCheck == btn) {
      break;
    }
  }
}

function clearDangerSign(){
    Array.prototype.forEach.call(btns,function(btn){
    btn.classList.remove('danger');
  });
}

UPDATE: Transitioned to using cleaner classList as per Another Solution

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

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

the best way to transfer a JavaScript value to a PHP page

I am experiencing an issue with an undefined function in my PHP page. I have tried everything and it just doesn't seem to work for me. Can anyone please assist me with this problem? <!DOCTYPE html> <html> <head> <scrip ...

iOS is causing issues with the JavaScript function and not allowing it to

By creating an NSString that contains JavaScript, I am able to set the e-mail body. NSString * someString =@"<!DOCTYPE html>\n <html>\n <body> \n <h1>My Web Page</h1> \n <p ...

Using Object Values and Subvalues to Assign Element Attributes in jQuery

I have a weekly schedule that I update regularly using a static table layout: <table> <tr class="live gm fsp"> <td>Oct. 7</td> <td>12:30 pm</td> <td class="prog">Show 1</td> <td>Team ...

Tips for setting cookie options in cookie-session version 1.0.2

Currently, I am delving into the intricacies of the "cookie-session" module in Node.js. https://github.com/expressjs/cookie-session My struggle lies in comprehending how to pass options for the cookie, particularly regarding expiration time. The default ...

Avoid refreshing AJAX on browser back navigation

Describing my current situation: I have a scenario with 2 pages: - On page 1, it sends a request using $.ajax to receive JSON data for display. Then there is a button that when clicked, takes me to page 2. - After clicking the button and transitionin ...

Disable the movement and dragging functionality of the scroll feature in Google Maps using React

I have a map.jsx file in my React application that contains the code below: import React from 'react'; import GoogleMapReact from 'google-map-react'; import './map.css'; const Map = ({ location, zoomLevel }) => ( <d ...

Issues with MP3 audio playback on Firefox and Firefox for Android browsers

Currently, I have integrated the Html5 audio tag into my website, only referencing mp3 audio format and not ogg. Surprisingly, everything seemed to be functioning perfectly when testing on a server with Firefox. However, once the same code was deployed ont ...

Extracting <p> elements from a separate HTML file and cycling through them

I successfully created a website using only HTML, JavaScript, and jQuery without any server-side scripting or language. Within my website, I have a simple stream.html page that remains unstyled with no CSS formatting. <html> <head> </head& ...

Scheduled Job unable to complete post request

(I am completely new to the world of JavaScript, node.js, and Heroku so I apologize in advance if my question is not very clear) I recently set up a Heroku node.js application with a scheduled task that should run every hour. The task does run as expecte ...

Having trouble with `request.auth.session.set(user_info)` in HapiJS?

I've encountered an issue with my strategy that is defined on a server.register(). Although I followed a tutorial, the code seems to be copied verbatim from it and now it's not functioning as expected. server.auth.strategy('standard&apo ...

What is the best method for comparing two JSON objects in AngularJS?

I am working with two JSON objects. $scope.car1={"Sedan":{"Audi":["A4","A3"]},"Hatchback":{"Maruthi":["Swift"]}}; $scope.car2={"Hatchback":{"Maruthi":["Swift"]},"Sedan":{"Audi":["A3","A4"]}}; I have attempted to compare these two objects using the co ...

Is it an issue with my code or Regex101? Diagnosing JavaScript/Node error

I'm currently working on an exercise assigned by my school which involves using regex. However, I'm facing some confusion regarding whether the issue lies in my function or in my regex code. Our instructor advised us to use regex101.com for testi ...

Using the same function in two different locations will only work for one instance

I have an AngularJS application where I am using a function called foo(bar) that takes bar as a parameter. The data for bar is retrieved from a web API, and I loop through this data using ng-repeat which works perfectly fine. <li class="list-group-item ...

The function in an AngularJS controller is failing to execute

I am experiencing an issue with calling the checkLogin function of a controller. The value returned by checkLogin is used to show/hide elements with ng-show. However, when debugging, I noticed that the execution stops after the function call and does not p ...

An uncomplicated broadcasting and receiving method utilizing an event emitter

This code is from chapter 3, example 11 of the book Node.JS in Action, found on page 52. var events = require('events'); var net = require('net'); var channel = new events.EventEmitter(); channel.clients = {}; channel.subscriptions = ...

What steps can I take to alter this situation?

I am working on creating an API Code. Here is the code I have written: When we run the code, it displays as follows: website <?php include('simple_html_dom.php'); $url = 'https://www.g2g.com/wow-us/gold-2299-19249?&server=30805&a ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

Looking for advice on utilizing Node.js and MongoDB to identify platform modifications on a website

I need guidance for a project I'm currently working on. The project involves extracting headers, like the example below in Mongo document format: { "url": "google.com", "statusCode": 301, "headers": { "location": "http://www.goog ...

Trigger an AJAX request by clicking a button using PHP

I've seen this question asked multiple times, but none of the answers seem to relate to my specific situation. I have a button that when clicked, should call a JavaScript function, passing it a PHP variable. The AJAX will then send that variable to a ...