Jeff Arries Jeff Arries - 1 year ago 50
HTML Question

Why doesn't my JS add an HTML class?

I've been messing with this code for a while now, and I can't seem to make it work. I made a

that is a green box and I want it to do my CSS transform when it is clicked on (by using JS to add a class), however that is not what it is doing right now. What rookie mistake did I make with this one?

Here's my code: There is also a JSFiddle here!

function box() { document.getElementById('box')[0].setAttribute("class", "box_ready");

body {
margin: 0;
padding: 0;

.container {
width: 800px;
margin: 0 auto;

#box {
width: 200px;
height: 200px;
background-color: #393;

#box:hover {
cursor: pointer;

.box_ready {
-webkit-animation: slide 2s;
animation: slide 2s;
animation-fill-mode: forwards;

@keyframes slide {
to {
-webkit-transform: translate(600px, 0px);
-ms-transform: translate(600px, 0px);
transform: translate(600px, 0px);
transform: rotateY(90deg);


/* Add WebKit when done*/

<div class="container">
<div id="box" onclick="box()"></div>

Answer Source

You are removing the existing class when you set the class HTML attribute. This removes the existing box class styling which makes the box disappear. You are also overriding the translate transform with the second transform CSS property.

Fixed JSfiddle:

Edit: notice, I changed the translate and removed the prefixed properties for clarity.