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:

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

Transferring and displaying messages between PHP scripts

On my page (index.php), I have a simple layout consisting of two DIVs. The left side (#leftDIV) contains a form and another DIV (#messages) for displaying error messages. On the right side, there is another DIV (#mapAJAX) which houses a PHP script responsi ...

Is there a problem with Framer Motion exit and AnimatePresence in Next.js?

Why isn't my exit prop or AnimatePresence working as expected? This is my custom variant: const imgVariant = { initial: { opacity: 0, y: -100, }, animate: { opacity: 1, y: 0, transition: { type: " ...

Leaflet.js obscuring visibility of SVG control

I am currently working with Leaflet 0.7.1 and I am looking to create a radial menu (similar to openstreetmap's iD editor) using d3 and display it on top of the map. I have come across some examples that use Leaflet's overlayPane to append the svg ...

Jspsych: Centering and aligning 3 p tags to the left on the page

Feeling pretty stuck at the moment. Here's what I have visually right now: I added a caption in Comic Sans and an arrow using MS Paint. Each line with color swatches is wrapped in a p tag. The goal is to center these p tags on the page (as they are ...

Updating AngularJS: Removing the hashtag using history.pushState()

Struggling to enhance the aesthetics of the URLs in my AngularJS application, I am facing some challenges. While I can access the "/" route without any issues, the "/about" route seems to be out of reach. Please note that the project is situated at (loc ...

Is it redundant to use flatMap in RXJS?

I recently came across an enlightening article on RXJS which delves into the concept of flatMap. After understanding its purpose - to flatten observable of observables into a single observable sequence (similar to SelectMany in C#) - I noticed an interes ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

Leveraging Webworkers in an Angular application for efficient data caching with service workers in the Angular-CLI

I am looking to run a function in the background using a worker, with data coming from an HTTP request. Currently, I have a mock calculation (e.data[0] * e.data[1] * xhrData.arr[3]) in place, but I plan to replace it with a function that returns the actual ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

Guide on setting up a new NPM and JavaScript project within Visual Studio 2015

Whenever I watch tutorials, they always mention having a "special npm reference" that I seem to be missing. All I can find are the "normal" references (.net assemblies). I also can't locate any project type labeled as pure "Javascript." I am current ...

PHP unable to retrieve ID from URL

Is there a way to extract an id from the URL when clicking a button for the purpose of deleting an item from a session? I have tried using $_GET but it doesn't seem to work. <form action="Shop.php?id= <?php echo $values["ProductCode"]; ?>" m ...

Identifying the method of navigation using PerformanceNavigationTiming

Previously, I was able to determine if a user had arrived on the page by clicking the back button in the previous page using window.performance.navigation.type like this: if (window.performance.navigation.type === 2) { window.location.reload() } Howe ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...

Utilizing a webkit transition to conceal a div element by setting its display property to "none"

I'm currently working with code that looks something like this: <style> #submenu { background-color: #eee; height:200px; width:400px; opacity: 1; -webkit-transition: all 1s ease-in-out; } .doSomething { ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

Encountering a parse error when making an AJAX call using structural functions

I'm in the process of developing an API and here is my PHP function. function retrieve_schools($cn){ $schools_query = "SELECT * FROM schools"; $school_result = mysqli_query($cn, $schools_query); $response_array['form_data'][&apo ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Concealing axis lines within the initial circular grid or opting not to include them

Is there a way to incorporate some whitespace within the center circle of the radar chart? I'm aiming for the axis to commence at 1 radius (the initial circular line) or perhaps have the stoke set to 0 for the primary radius. Any assistance would be g ...

Issue: Bidirectional binding functionality is not functioning properly within the user interface modal

I'm currently working on displaying data in a modal, but I'm facing issues with getting two-way binding to work properly. In my HTML code: <div class="cta-actions"> <div class="action"><a class="btn btn-lg btn-max">Send a pa ...

Is there a way to use a Google Chrome command line switch to simulate the dimensions of a

Seeking information on the available Google Chrome command line switches for emulating device sizes. Specifically, I need to test a component that utilizes CSS @media queries for min-device-width/min-device-height. Previous attempts with --window-size an ...