-2

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 class="uno">COSA È</p>
  </div>

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

drMAIN
  • 76
  • 7

2 Answers2

3

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 class="uno">COSA È</p>
</div>
Tom
  • 4,972
  • 3
  • 10
  • 28
  • You could even remove the `buttonChange` function entirely and just add the eventListener. Remember your JS must then run at the bottom of the body element (or at least after wherever your button's HTML is). – Nicolas Goosen Feb 28 '22 at 10:43
-1

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.

  • 1
    Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Please _never_ suggest or encourage these attributes. The last browser that still needs them reached end of life nearly two decades ago. Why would you change the style explicitly if OP’s code already correctly toggles the CSS class? – Sebastian Simon Feb 28 '22 at 10:44