Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to an element using event.currentTarget.className

I have a button with a yellow background, upon clicking the button I would like it to turn black(https://jsfiddle.net/dcq5v6hy/1/). I am trying to do this with a js function and a button.active css class (I have never seen .active, but I am trying to follow a W3Schools tutorial).

function changeColor(evt) {
  evt.currentTarget.className += "active";
}
.tab button {
  background-color: yellow;
}


/* Create an active/current tablink class */

.tab button.active {
  background-color: red;
}
<div class="tab">
  <button onclick="changeColor(event)">Click Me</button>
</div>

As you can see, nothing happens when the button is clicked. How can I fix this?

like image 263
Justin Avatar asked Sep 04 '26 03:09

Justin


1 Answers

Try preppending a space in the appended string: evt.currentTarget.className += " active";

like image 82
Chad.Glazier Avatar answered Sep 05 '26 17:09

Chad.Glazier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!