Search code examples
jquerycsstoggleclass

CSS transform using jQuery toggleClass


I have a think like this

http://donkey.ninja/test/

When the button is clicked, jquery toggles class:

.trans {
    background-color: #ABC;
    transform: translateX(100px) scale(0.5) rotate(180deg);
}

On the <div class="container2">

And when you click the button again, the class is toggled again and the div becomes black and returns to its original position.

When I use jquery to add the style responsible for transform using following code:

$('.trans').css({"transform":"translateX(100px) scale(0.5) rotate(180deg)"});

I get something like this:

http://donkey.ninja/test2/

Problem: The div transforms when clicked, but it doesn't transform back when clicked again, only the color changes back.

Why is that? What's the difference between declaring it in css stylesheet and adding it with jQuery?


Solution

  • When you use jQuery selector .trans you add styles not to class (like using CSS), but to DOM-element. So, when you remove class, styles does not remove.

    If you want to change CSS using jQuery, you may append style-element to body. Like this:

    $('<style>.trans { transform: translateX(100px) scale(0.5) rotate(180deg); }</style>').appendTo('body');