2

I have a demo code here

I have a bar with separate blocks in it and a marker on top that can be positioned along the bar.When the marker is on top of a particular block I want to color that block.

This is working but I want each block to be a different color. I have a color class on each block that will work with 'selected' added to the end.The color class is like 'bar-item-yellow' Is it possible to add 'selected' to a class that contains 'bar-item-'

const marker = document.querySelector('.bar-marker')

const bars = document.querySelectorAll('.bar-item');

(function() {
    for(let i=0; i<=bars.length; i++){
      if(marker.offsetLeft > 
         bars[i].offsetLeft && marker.offsetLeft < 
         bars[i].offsetWidth+bars[i].offsetLeft){
         bars[i].classList.add('bar-item--selected')
      }
    }
})();
Naveen
  • 1,441
  • 2
  • 16
  • 41
ttmt
  • 5,822
  • 27
  • 106
  • 158
  • 1
    https://stackoverflow.com/questions/195951/how-to-change-an-elements-class-with-javascript ? – Félix Paradis Aug 20 '19 at 13:01
  • 1
    You need a selector like `.bar-item-red.bar-item--selected`, this will target any element that has both classes. Not sure what the SCSS version of that is. –  Aug 20 '19 at 13:11
  • 2
    It would be simpler if you just added `selected` class and combine them in your SCSS declaration like this: `&-red.selected{ background: red; }` – Kaddath Aug 20 '19 at 13:13
  • 1
    I did `var barColors = ["red", "yellow", "blue", "green"];` `bars[i].classList.add(bar-item-'+barColors[i]+'-selected);` and it worked fine. But you will need to make sure it doesn't go outside of the color array – Pierre-Yves Legeay Aug 20 '19 at 13:13
  • I was about to write the answer you are looking for but the post has been closed :( – Omri Attiya Aug 20 '19 at 13:18
  • Here's one way: https://jsfiddle.net/khrismuc/cexznw96/ (did a few other changes) –  Aug 20 '19 at 13:22
  • Better way, using jQuery: https://jsfiddle.net/khrismuc/qonh3z5j/ –  Aug 20 '19 at 13:41

0 Answers0