Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Toggle class with inline onClick?

Tags:

javascript

css

I am trying to replicate the css transition here.

Similar to the example, I have created:

<span onclick="document.getElementById('box').classList.toggle('grow');">Go</span>

<div class="box"></div>


.box {
width: 150px;
height: 150px;
background-color: red;
border: 1px solid #000;
transition-property: all;
transition-duration: .5s;
transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
}

.grow {
 width: 350px;
}

https://jsfiddle.net/swrhho41/15/

However, this doesnt seem to work. The grow class isn't being added to the div.

Is there more JS that is needed?

like image 411
MeltingDog Avatar asked Sep 23 '26 21:09

MeltingDog


1 Answers

box is not an id. It's a class.

Therefore, your document.getElementById selects nothing. Simply change it to,

document.getElementsByClassName('box')[0].classList.toggle('grow');

Here's the fiddle

like image 123
choz Avatar answered Sep 25 '26 10:09

choz



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!