skip to Main Content

I have these four divs with same class-name and want to change color everytime when I click on them but the trick is that if I click on first div its color will change and when I click to next div the previous color should comes to its default color and the one I clicked should change.

<div class="box">Box1</div>     
<div class="box">Box2</div>     
<div class="box">Box3</div>    
<div class="box">Box4</div>  

enter image description here

Like this…..NA

3

Answers


  1. What you wrote in the description of the problem isn’t really the same as what you wrote in the question title, but I think I should answer what’s described, to achieve this functionality using JavaScript, here’s an example code snippet that demonstrates how to change the color of the clicked box while reverting the color of the previously clicked box back to its default color;

      // get all elements with the "box" class
      const boxes = document.querySelectorAll('.box');
    
      let prevBox = null; // store the previously clicked box
    
      // add click event listeners to each box
      boxes.forEach(box => {
        box.addEventListener('click', () => {
          if (prevBox !== null) {
            prevBox.style.backgroundColor = 'lightgray'; // revert the previous box color
          }
          box.style.backgroundColor = 'red'; // change the clicked box color
          prevBox = box; // store the clicked box as the previous box
        });
      });
    .box {
        width: 100px;
        height: 100px;
        background-color: lightgray;
        text-align: center;
        line-height: 100px;
        cursor: pointer;
        margin: 5px;
    }
    <div class="box">Box1</div>
    <div class="box">Box2</div>
    <div class="box">Box3</div>
    <div class="box">Box4</div>
    Login or Signup to reply.
  2. You can simply use the JavaScript methods to achieve this even without using the loops.
    Check the code below..

    const boxContainer = document.querySelector('.box-container');
    
            boxContainer.addEventListener('click', (event) => {
                const clickedBox = event.target;
                if (clickedBox.classList.contains('box')) {
                    const prevSelectedBox = boxContainer.querySelector('.selected');
                    if (prevSelectedBox) {
                        prevSelectedBox.classList.remove('selected');
                    }
                    clickedBox.classList.add('selected');
                }
            });
            .box {
                width: 100px;
                height: 100px;
                background-color: lightgray;
                text-align: center;
                line-height: 100px;
                cursor: pointer;
                margin: 5px;
            }
    
            .selected {
                background-color: red;
            }
        <div class="box-container">
            <div class="box">Box1</div>
            <div class="box">Box2</div>
            <div class="box">Box3</div>
            <div class="box">Box4</div>
        </div>
    Login or Signup to reply.
  3. <html>
    <head>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background-color: gray;
        margin: 10px;
        text-align: center;
        line-height: 100px;
        cursor: pointer;
      }
    </style>
    </head>
    <body>
    
    <div class="box">Box1</div>
    <div class="box">Box2</div>
    <div class="box">Box3</div>
    <div class="box">Box4</div>
    
    <script>
    document.addEventListener("DOMContentLoaded", function() {
      let previousBox = null;
    
      const boxes = document.querySelectorAll('.box');
      boxes.forEach(box => {
        box.addEventListener('click', function() {
          if (previousBox !== null) {
            previousBox.style.backgroundColor = 'gray';
          }
    
          this.style.backgroundColor = getRandomColor();
          previousBox = this;
        });
      });
    
      function getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      }
    });
    </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search