Reputation: 12689
So I've managed to create a rotation that only rotates in one direction by using a setTimeout
. I was wondering if I could still achieve this without using it. The main issue I have is that if I click fast enough, it will still spin the other way.
So overall, is there a way to make it spin in one direction regardless of how fast I click.
function clicked()
{
element = $("#spin");
if ($(element).hasClass("rotate2"))
{
$(element).removeClass("rotate rotate2");
setTimeout( () => $(element).addClass("rotate"), 1);
}
else if($(element).hasClass("rotate"))
{
$(element).addClass("rotate2");
}
else
{
$(element).addClass("rotate");
}
}
div.horizontal {
position: absolute;
width: 100%;
height: 5px;
background-color: red;
top: 50%;
transform: translateY(-50%);
}
div.horizontal.rotate {
transform: translateY(-50%) rotate(-180deg);
transition: transform 0.5s;
}
div.horizontal.rotate2 {
transform: translateY(-50%) rotate(-360deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width: 50px; height: 50px; position: relative;">
<div id="spin" class="horizontal">
</div>
</div>
<button onclick="clicked()">Rotate</button>
Upvotes: 1
Views: 64
Reputation: 53709
You can just use a single class for the transition, and remove the class on transitionend
var $button = $('#button'),
$spin = $('#spin');
$(document).on('click', $button, function() {
$spin.addClass('rotate').on('transitionend',function() {
$(this).removeClass('rotate');
});
})
div.horizontal {
position: absolute;
width: 100%;
height: 5px;
background-color: red;
top: 50%;
}
div.horizontal.rotate {
transform: rotate(-180deg);
transition: transform .5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width: 50px; height: 50px; position: relative;">
<div id="spin" class="horizontal">
</div>
</div>
<button id="button">Rotate</button>
Upvotes: 1