"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I Rotate an Image on Click using CSS3 Transform?

How can I Rotate an Image on Click using CSS3 Transform?

Published on 2024-11-08
Browse:642

How can I Rotate an Image on Click using CSS3 Transform?

CSS3 Transform on Click using Pure CSS

In an effort to enhance user interaction, you may encounter the need to transform an element upon click using CSS3. Specifically, rotating an image to create a cross symbol is a common task. While hovering is a common trigger for transformation, this article explores the possibility of using the onClick event exclusively through CSS.

Initially, the provided code utilizes the hover event to rotate the image by 45 degrees. However, to trigger the transformation on click, a modification is required.

Active State Transformation

CSS offers the :active pseudo-class which is designed to style elements when they are being clicked. By leveraging this pseudo-class, you can achieve the desired behavior:

.crossRotate:active {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
}

This code will rotate the image 45 degrees when it is clicked. However, it's important to note that the transformation will vanish once the click is released. This is because the :active state is only active during the click itself.

Preserving Transformation with JavaScript

If you want the transformation to persist after the click, you'll need to employ JavaScript. By capturing the click event using jQuery, you can toggle the transformation using the css() method:

$( ".crossRotate" ).click(function() {
  if (  $( this ).css( "transform" ) == 'none' ){
    $(this).css("transform","rotate(45deg)");
  } else {
    $(this).css("transform","" );
  }
});

In this code, the transform property is checked. If it's set to none, the transformation is applied, otherwise it is removed. This allows you to toggle the cross symbol on and off with each click.

By utilizing these techniques, you can effectively rotate an image using CSS3 transform on click, both with and without JavaScript to maintain the transformation beyond the click event.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3