I have image and two buttons that should rotate that image 45 or -45 degrees.
<div>
<img src="/assets/img1.png">
</div>
<div>
<button type="submit">rotate left 45</button>
<button type="submit">rotate right 45</button>
</div>
How can I make function that will apply css transform rotate to this image? Steps should be in 45deg ether way and it should constantly rotate no matter how many times user click on button.
You could update the elements CSS transform property on click.
let rotationAmount = 0;
function rotateImage(direction) {
rotationAmount += direction == 'left' ? -45 : 45;
document.querySelector('#image').style.transform = `rotate(${rotationAmount}deg)`;
}
#image {
height: 100px;
width: 100px;
}
.button-wrapper {
margin-top: 30px;
}
<div>
<img id="image" src="">
</div>
<div class="button-wrapper">
<button type="submit" onclick="rotateImage('left')">rotate left 45</button>
<button type="submit" onclick="rotateImage('right')">rotate right 45</button>
</div>