I have a simple image I flip on top when it is clicked. I use jQuery to call the respond to clicks.
Now I am also hiding and showing elements which works every time, but the rotation only works on every second attempt, which means every fourth click.
Click one: rotate 180 Click two: rotate back. Click three: no rotation Click four: no rotation
it repeats then.
Why is this?
let isRotated = false;
$(".buttonLayout").on("click", function() {
var classTohide = ".classToHide";
if (!isRotated) {
$(classTohide).hide()
isRotated = true
$(this).toggleClass("rotate-180");
} else {
$(classTohide).show()
isRotated = false
$(this).toggleClass("rotate-180back");
}
});
.rotate-180 {
transform: rotate(180deg);
}
.rotate-180back {
transform: rotate(0deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://via.placeholder.com/100" id="@position" />
CodePudding user response:
You are using toggleClass
, which removes the class, if the element has it and vice versa. So every second "round" of clicking, the class gets removed, when it should be added.
Change your code to this:
let isRotated = false;
$(".buttonLayout").on("click", function() {
if (!isRotated) {
isRotated = true;
//add one class and remove the other
$(this).addClass("rotate-180");
$(this).removeClass("rotate-180back");
} else {
isRotated = false;
//add one class and remove the other
$(this).addClass("rotate-180back");
$(this).removeClass("rotate-180");
}
});
.rotate-180 {
transform: rotate(180deg);
}
.rotate-180back {
transform: rotate(0deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://via.placeholder.com/100" id="@position" />