jQuery rotate div onclick +/-90

17,694

Solution 1

You could use toggleClass and apply css transform to that class:

$('button:first-of-type').on('click', ()=> $('#rotate').toggleClass('rotated'));

const btn = document.querySelector('button:nth-of-type(2)');
const block2 = document.querySelector('#rotate2');

btn.addEventListener('click', ()=>block2.classList.toggle('rotated'));
body {text-align: center;}
#rotate, #rotate2 {
  width: 100px;
  height: 100px;
  background: red;
  border-top: 10px solid black;
  transition: transform .2s ease;
  margin: 20px auto;
  color: #fff;
}

.rotated { 
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>rotate block</button>

<div id="rotate">jQuery</div>

<button>rotate block</button>

<div id="rotate2">Vanilla</div>

Solution 2

You need to use CSS for rotating the div. And for +-90 you have to add/remove to the div, this can be easy achieved with toggleClass. Adding this behaviour inside a click event will result something like below.

$('.square').click(function() {
    $(this).toggleClass('rotate-90');
});
.square {
  width: 150px;
  height: 100px;
  background-color: red;
}

.rotate-90 { 
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square">
  
</div>

Share:
17,694
Yanlu
Author by

Yanlu

UI/Webdesigner Founder of Hawcons - a free library of over 500+ free UI icons

Updated on June 05, 2022

Comments

  • Yanlu
    Yanlu almost 2 years

    I was wondering if there is an easy way to rotate a div +90 degrees after clicking it and by clicking it next time it returns to 0 degrees (so that the div rotates -90 degrees). Since I couldn't find anything I was looking for your help. Thanks.

  • Yanlu
    Yanlu almost 9 years
    Thanks, that was excactly what I was looking for! I made it a little bit smoother with CSS3 transition For example: -webkit-transition: all 1s ease; Fiddle
  • prettyInPink
    prettyInPink almost 9 years
    Great, happy to help. Instead of adding 'all', you can also add the transition to the transform only: #rotate{ width: 100px; height: 100px; background: red; margin: 50px; text-align: center; -webkit-transition: transform 1s ease; -moz-transition: transform 1s ease; -ms-transition: transform 1s ease; -o-transition: transform 1s ease; transition: transform 1s ease; }
  • Kunj
    Kunj over 6 years
    It is probably the best solution without using any plug-ins or function.