3

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?

2
  • 2
    No, I didnt think you needed it Commented Dec 6, 2016 at 0:28
  • Looks like your onclick handler is looking for a div with an ID of 'box' and you're HTML has a div with a class of 'box'. Commented Dec 6, 2016 at 0:29

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

0

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')

Comments

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

</div>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.