MeltingDog
MeltingDog

Reputation: 15404

JavaScript: Toggle class with inline onClick?

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?

Upvotes: 3

Views: 6915

Answers (4)

Yaman
Yaman

Reputation: 1061

<div id="box" class="box">

</div>

you are retrieving the item by Id, so Id should be box

Upvotes: 0

hackerrdave
hackerrdave

Reputation: 6706

Since 'box' is a className, you need to either set the element's ID to be "box":

<div id="box"></div> 

Or update your selector to be:

document.querySelector('.box').classList.toggle('grow')

Upvotes: 0

JanR
JanR

Reputation: 6132

The problem is your onclick code is looking for an id : getElementById

Yet your div has a class not an id, change it to

<div id="box"></div>

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

make sure to also update your css if you update it to id:

#box {
width: 150px;
/* etc */

Also if you want it to grow, make the width on the .grow !important.

Fiddle: https://jsfiddle.net/swrhho41/18/

Upvotes: 1

choz
choz

Reputation: 17858

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

Upvotes: 7

Related Questions