ArticleZip > Css Animation Toggle Rotate On Click

Css Animation Toggle Rotate On Click

CSS Animation Toggle Rotate on Click

Have you ever wanted to add some fun interactivity to your website by making elements rotate when clicked? Well, you’re in luck because in this article, we’ll walk you through how to create a CSS animation toggle that rotates an element when clicked.

To achieve this effect, we’ll be using a combination of HTML, CSS, and a sprinkle of JavaScript. Remember, this technique is purely achieved through CSS animation, so no need to worry about diving into complex JavaScript code.

Let’s start by setting up our HTML structure. We simply need an element that we want to rotate on click. For this example, let’s use a simple div element.

Html

<div class="rotate-box"></div>

Next, we move on to the CSS styling. We’ll define the initial state of our element and the animations that will be triggered on click.

Css

.rotate-box {
  width: 100px;
  height: 100px;
  background-color: #3498db;
  transition: transform 0.5s;
}

.rotate-box.rotate {
  transform: rotate(180deg);
}

In the CSS code snippet above, we’ve defined a basic style for our `.rotate-box` element. The `transition` property ensures that any changes to the `transform` property will be animated over a duration of 0.5 seconds. We’ve also created a separate CSS class called `.rotate` that will apply a rotation of 180 degrees when added to our element.

Now, let’s add the interactivity using JavaScript. We’ll listen for a click event on our element and toggle the `.rotate` class to trigger the rotation animation.

Javascript

document.querySelector('.rotate-box').addEventListener('click', function () {
  this.classList.toggle('rotate');
});

In the JavaScript code above, we used `querySelector` to select our `.rotate-box` element and added a `click` event listener to it. When the element is clicked, the `toggle` method is called on the `classList` property to add or remove the `.rotate` class, thereby triggering the rotation animation.

And there you have it! A simple yet effective way to add interactive CSS animations to your website. Feel free to customize the styles and animations to suit your design preferences.

In conclusion, adding a CSS animation toggle to rotate an element on click is a great way to enhance user interaction on your website. By combining HTML, CSS, and a dash of JavaScript, you can create engaging animations with ease.

We hope this tutorial has been helpful, and we can’t wait to see how you incorporate this technique into your web projects. Happy coding!

×