I'm trying to make an icon button to rotate on click, but every time I remove the class, it spins backwards, I wanted to do in a way that every time it's clicked, it only spins clockwise.
const btn = document.querySelector('.reset-button');
btn.addEventListener("click", (e) => {
btn.classList.add("rotate");
setTimeout(() => {
btn.classList.remove("rotate");
}, 1500);
});
div {
display: flex;
flex-direction: row;
justify-content: center;
}
.reset-button {
transition: 1.5s;
}
.rotate{
transform: rotate(720deg);
}
<link rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Material Symbols Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
<div>
<button ><span >
refresh
</span></button>
</div>
CodePudding user response:
You want the transition effect to occur only as the element transitions from 0 rotation to 720deg.
In the other direction (720deg to 0deg) you want it to happen instantly so the user sees no change.
Remove the transition from where it is and have it only on the rotating class.
const btn = document.querySelector('.reset-button');
btn.addEventListener("click", (e) => {
btn.classList.add("rotate");
setTimeout(() => {
btn.classList.remove("rotate");
}, 1500);
});
div {
display: flex;
flex-direction: row;
justify-content: center;
}
.reset-button {}
.rotate {
transform: rotate(720deg);
transition: 1.5s;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material Symbols Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
<div>
<button ><span >
refresh
</span></button>
</div>
CodePudding user response:
While this might be on purpose, notice that besides for rotating back, your code doesn't rotate the button at all the first time it's clicked after the page is loaded.
Here's an alternate option (not the only way to do this) that rotates the button even when you click on it for the first time after the page was loaded in case that is of use to anyone.
const btn = document.querySelector('.reset-button');
btn.addEventListener("click", (e) => {
btn.style.transition = '1.5s';
btn.style.transform = 'rotate(720deg)';
setTimeout(() => {
btn.style.transition = '0s';
btn.style.transform = 'rotate(0deg)';
}, 1500);
});
div {
display: flex;
flex-direction: row;
justify-content: center;
}
.reset-button {}
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material Symbols Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
<div>
<button ><span >
refresh
</span></button>
</div>