Home > Software engineering >  trying to make a div change color and text on click, every click
trying to make a div change color and text on click, every click

Time:08-03

I'm trying to have div on the First click change the text to ON and its color to yellow.

and the second click changes the text back to OFF and its color to gray.

But I can't find a solution to it, thanks for helpers

<div  onclick="onBall3Click()">
        OFF
</div>




function onBall3Click() {

            // when the user click chnage button to yellow and text to on  
            // when user click again change background to gray and text to off

            var ball3 = document.querySelector('.ball3');

            alert('Ball3');

            ball3.style.backgroundColor = 'yellow'
            ball3.innerText = 'ON'

            if (ball3.innerText == 'ON') {
                ball3.style.backgroundColor = 'gray'
                ball3.innerHTML = 'OFF'
            }

        }

CodePudding user response:

I think it has something to do with you adding your "onclick" event to the div as if it is a button.

Try adding an event listener:

ball3.addEventListener('click', onBall3Click);

And adding changing your if statement for it to work (You are changing the text to "ON" then changing it back to "OFF")

if (ball3.innerText == 'ON') {
                ball3.style.backgroundColor = 'gray'
                ball3.innerHTML = 'OFF'
            }

else if (ball3.innerText == 'OFF') {
                ball3.style.backgroundColor = 'yellow'
                ball3.innerHTML = 'ON'
            }

I would suggest you add a boolean to check what the status of the div is, but that is totally up to you:


bool BallStatus = true;

if (!BallStatus) {
                ball3.style.backgroundColor = 'gray'
                ball3.innerHTML = 'OFF'
            }

else if (BallStatus) {
                ball3.style.backgroundColor = 'yellow'
                ball3.innerHTML = 'ON'
            }

CodePudding user response:

the solution is based on adding an eventListener to your code like this:

 let ball3 = document.querySelector('.ball3');
 ball3.addEventListener("click", onBall3Click, false); 

function onBall3Click() {

  alert('Ball3');

  if (ball3.innerText === 'ON') {
    ball3.style.backgroundColor='gray';
    ball3.innerHTML = 'OFF'
  }else if(ball3.innerText === 'OFF'){
    ball3.style.backgroundColor='yellow';
    ball3.innerHTML = 'ON'
  }
}

Now javascript listens when you click on the element with ball3 class3 and the behavior is as expected.

  • Related