0

I have a problem, I want to make clickable boxes (span class="label") like this:

  • first click = changing background to red,
  • second click = background change to blue,
  • third click = no color.

However, counting a click is not on each box separately, only globally. For example, first click on box number 1 and we have a red color (this is OK), but the second click on box number X appears blue, but should be counted as the first click on this box.

The second problem is that after pressing the button "new task", the new boxes are no longer attached to the function changeColor().

My codepen: `https://codepen.io/klaudiabudzisch/pen/QooOXV `

My code:

<section class="daily-task">
<!-------- title -------->
  <div class="header one">
    <button id="addDaily">new task</button>
    <h1>Daily Tasks</h1>
  </div>

<!-------- tasks -------->

  <div id="daily" class="task">
        <div class="task-text">
                <input type="text" class="text">
        </div>
        <div class="box-numbers">
                <span class="label">1</span>
                <span class="label">2</span>
                <span class="label">3</span>
                <span class="label">4</span>
                <span class="label">5</span>
                <span class="label">6</span>
                <span class="label">7</span>
                <span class="label">8</span>
                <span class="label">9</span>
                <span class="label">10</span>
        </div>
  </div>
</section>


 **CODE JS** 


const dailyBtn = document.getElementById("addDaily");

dailyBtn.addEventListener("click", function() {
  const boxes = document.getElementById("daily");
  const clone = boxes.cloneNode(true);
  boxes.parentNode.appendChild(clone);
 });


 let box = document.querySelectorAll("span.label");
 let clicks = 0;

 Array.from(box).forEach(e => {
  e.addEventListener('click', changeColor);
});

function changeColor() {
    clicks++;
  if (clicks == 1) {
    this.style.backgroundColor ='red';
} if (clicks == 2) {
  this.style.backgroundColor = 'blue';
} if (clicks == 3) {
  this.style.backgroundColor = 'red';
} if (clicks == 4) {
  this.style.backgroundColor = '';
  clicks = 0;
}
}

Could you please tell me what am I doing wrong? Is what I wrote correct at all?

Klaudia
  • 49
  • 6

0 Answers0