Home > database >  change color with click on js
change color with click on js

Time:03-01

i want change the color of this div when i click on it i try to use this javascript but nothing,

const buttonChange = () => {

  const button = document.querySelector('.uno');
  button.addEventListener('click', () => {
    button.classList.toggle('.uno-active');
  })



}
.uno{
color: rgb(12, 114, 231);
background-color: rgb(255, 255, 255);
}
.uno-active{
    color: rgb(255, 255, 255);
    background-color: rgb(11, 28, 47);;
    
}
<div>
            <p >COSA È</p>
  </div>

////////////////////////////////

CodePudding user response:

You have to call the buttonChange() function if you want to handle the click event. Also you don't have to put a dot before "uno-active" :

const buttonChange = () => {
  const button = document.querySelector('.uno');
  button.addEventListener('click', () => {
    button.classList.toggle('uno-active');
  });
}
buttonChange();
.uno{
  color: rgb(12, 114, 231);
  background-color: rgb(255, 255, 255);
}

.uno-active{
  color: rgb(255, 255, 255);
  background-color: rgb(11, 28, 47);
}
<div>
  <p >COSA È</p>
</div>

CodePudding user response:

Use <div id="yourID" onclick="javascript:yourFunction();"></div> for calling the right JS/Jquery function and use function myFunction() { document.getElementById("yourID").style.background = "#000"; } to give the style.

Here is aJSfiddle.

  • Related