Yanlu
Yanlu

Reputation: 335

jQuery rotate div onclick +/-90

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.

Upvotes: 3

Views: 19425

Answers (2)

prettyInPink
prettyInPink

Reputation: 3444

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>

Upvotes: 10

adricadar
adricadar

Reputation: 10209

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>

Upvotes: 3

Related Questions