Click to Rotate Image Icon

I could use some assistance with this task. I want to create a functionality where clicking on the text/icon causes the + icon to rotate 45 degrees, resembling an x icon. With each subsequent click, the icon should alternate between the + and x shapes.

Any assistance offered would be greatly valued!

JSFIDDLE

https://jsfiddle.net/d264kt2t/

HTML

<div class="container">

<div class="pointer">
CLICK ME<img src="http://www.ssglobalsupply.com/images/plus.png" class="coolImage">
</div>

</div>

CSS

.container{
  width:100%;
  padding-top:100px;
  padding-bottom:100px;
  background-color:#000;

}

.coolImage{
  height:17px;
  width:17px;
  margin-left:7px;
}

.pointer{
  cursor:pointer;
  text-align:center;
  font-size:20px;
  color:#fff;
}

Answer №1

Chic and elegant animation

Personally, I found Louys' solution to be excessively wordy and unengaging.

With the power of jQuery at our fingertips, we can craft a much more visually appealing alternative:

rotated = false;
$('.pointer').click(function(){
  elem = this;
  
  $({rotation: 225*rotated}).animate({rotation: 225*!rotated}, {
    duration: 500,
    step: function(now) {
      $(elem).css({'transform' : 'rotate('+ now +'deg)'});
    }
  });
  rotated=!rotated;
});

Check out the JSFiddle or the code snippet below:

i = 1;
$('.pointer').click(function(){
  elem = $(this).children("img")[0];
  
  $({rotation: 225*!i}).animate({rotation: 225*i}, {
    duration: 500,
    step: function(now) {
      $(elem).css({'transform' : 'rotate('+ now +'deg)'});
    }
  });
  i=!i;
});
.container{
  width:100%;
  padding-top:100px;
  padding-bottom:100px;
  background-color:#000;
  text-align:center;
  font-size:20px;
  color:#fff;
}

.coolImage{
  height:17px;
  width:17px;
  margin-left:7px;
}

.pointer{
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="pointer">
CLICK ME<img src="https://i.sstatic.net/Tgf0C.png" class="coolImage">
</div>

</div>

We utilize jQuery#animate with a "fake" object to achieve the smooth animation effect. Adjust the duration parameter to change the speed of the animation to your liking.

The variable rotated serves as a placeholder for implementing the toggle functionality.

If you need further clarification, feel free to ask.

Answer №2

Create a CSS class called 'rotated' that defines the rotation effect, then use JavaScript to toggle this class on click events. Here is an example code snippet:

var pointers = document.getElementsByClassName('pointer');
for(var i = 0; i < pointers.length; i++){
pointers[i].addEventListener('click', function(event) {
  event.target.getElementsByClassName('coolImage')[0].classList.toggle('rotated');
  });
}
.container{
  width:100%;
  padding-top:100px;
  padding-bottom:100px;
  background-color:#000;
  text-align:center;
  font-size:20px;
  color:#fff;
}

.coolImage{
  height:17px;
  width:17px;
  margin-left:7px;
  transform:rotate(45)
}

.pointer{
  cursor:pointer;
}

.rotated {
  transform: rotate(45deg);
}
<div class="container">

<div class="pointer">
CLICK ME<img src="http://www.ssglobalsupply.com/images/plus.png" class="coolImage">
</div>

</div>

Answer №3

Here is a functional example that works across different browsers:

function rotate() {
   var element = document.getElementById('imgToRotate');
   var className = element.className;
   if(className.indexOf('rotate') === -1) {
      element.className = element.className + ' rotate';
   } else {
      element.className = element.className.replace(' rotate', '');
   }
}
.container{
  width:100%;
  padding-top:100px;
  padding-bottom:100px;
  background-color:#000;
  text-align:center;
  font-size:20px;
  color:#fff;
}

.coolImage{
  height:17px;
  width:17px;
  margin-left:7px;
}

.pointer{
  cursor:pointer;
}

.rotate {
  transform:rotate(45deg);
  /* Firefox */
    -moz-transform:rotate(45deg);
    /* Safari and Chrome */
    -webkit-transform:rotate(45deg);
    /* Opera */
    -o-transform:rotate(45deg);
    /* IE9 */
    -ms-transform:rotate(45deg);
    /* IE6,IE7 */
    filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476);
    /* IE8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; 
}
<div class="container">

<div class="pointer" onclick="rotate()">
CLICK ME<img src="http://www.ssglobalsupply.com/images/plus.png" class="coolImage" id="imgToRotate">
</div>

</div>

Check out the JSFiddle link for live demonstration: https://jsfiddle.net/balasuar/jcwg1h71/

Answer №4

I have made an update to your Fiddle by incorporating the following script:

var rotated = false;
$(".pointer").click(function() {
  if (!rotated) {
    $(this).find("img").css({
      "transform": "rotate(45deg)"
    });
  } else {
    $(this).find("img").css({
      "transform": "rotate(0deg)"
    });
  }
  // Toggle the flag
  rotated = !rotated;
});

Please note: I have also included the jQuery library in the external resources.

Answer №5

Please add the following code within the <img> element:

onclick="this.style['-webkit-transform'] = 'rotate(' + 45 + 'deg)';"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way in Material UI to dynamically update the border color of a TextField once the user inputs text?

Is there a way to style the border of a TextField only when it has text input? I am currently using the outlined version of the TextField, which displays placeholder text when empty. <TextField variant="outlined" /> So far, I have managed ...

Error: Attempting to access property 'setData' of an undefined object results in a TypeError [Slider]

I encountered an error with my slider that says Uncaught TypeError: Cannot read property 'setData' of undefined. The error occurs when I use material ui as a component along with redux-form. This issue happens specifically when the slider is bein ...

Content must be concealed following the third paragraph

Dealing with an API that generates content in p tags, which can become excessively long. Considered hiding the content after 400 characters, but it poses a risk of cutting through HTML tags. Instead, looking to hide the excess content after 3 paragraphs a ...

How can I center the navbar logo and use it as a toggle for collapsing the menu?

This is a simple example of a navigation bar <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class ...

Mix div borders with varying border radius for child elements

I'm currently working on a project that involves creating border lines between divs to achieve a design similar to the one shown in this design jpeg. However, I've only managed to reach an output jpeg where the merging is not quite right. The C ...

Technique for identifying a sequence within a longer numerical series

As I ponder this puzzle for what seems like an eternity, I humbly turn to you for a possible solution. A lengthy number resembling this one: 122111312121142113121 It is crucial to note that no numbers exceed four or fall below one. Now my quest is to une ...

Struggling to retrieve the value from ng-model?

Currently, I am utilizing this account due to being logged into Facebook on my other account and not having access to my phone for the verification code process. On another note, I am struggling to retrieve the value from an ng-model despite numerous atte ...

Select either one checkbox out of two available options

My form includes two checkboxes, allowing users to click on both of them. I'm wondering if it's possible to set it up so that only one checkbox can be selected at a time. For example, clicking on the first checkbox would turn it on while turning ...

export module from the express framework

function affirm(){ console.log("yes") } Element={} Element=affirm Element.something="something" Element.nothing="nothing" DEPICTED IN WEB BROWSER: In the code snippet above, if you were to console.log(Element), it would display ...

"Utilize jQuery to swap out anchor tags with their corresponding href URLs within a

Is there a way to transform anchor tags within a string into plain text links? Original: let text = "This is a sample article with embedded links that should be converted. < a href=" http://local.mysite.com/test/f/english-as-a-second/p/addpost">loc ...

Tips for Utilizing Environmental Variables within a Vue Application's index.html File

My website has an index file with all the necessary meta tags, stylesheets, and scripts: <!DOCTYPE html> <html lang="en"> <head> <!-- Required Meta --> <meta charset="UTF-8"> <meta http-equi ...

Customizing the display field in an ExtJs Combobox

I am working on a java web application that utilizes an entity class to populate a combobox with ExtJs. The issue I am facing is as follows: Some entries in the displayField may contain html code. To prevent any issues, I used flexjson.HTMLEncoder during ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...

Testing AJAX requests across different domains on a local server setting

While working in my local development environment at , I encountered the need to make an Ajax call to open a URL and display the response in fancybox. Due to the local development environment, this creates a cross-domain issue. However, once deployed to ...

Order of tabs, dialog, and forms customization using Jquery UI

I'm currently working on a jquery dialog that contains a form split into multiple tabs. In order to enhance keyboard navigation, I am looking for a way to make the tab key move from the last element of one tab to the first element of the next tab. Cur ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

Having trouble configuring a basic express server to host a static JavaScript file

Struggling to set up a basic Express server with accompanying HTML and JS files. Despite multiple attempts, I can't get the JS file to properly load. index.js: const express = require("express"); const app = express(); const path = require ...

How do you start the React number input control with an empty value?

My goal is to have the input field initially empty when controlled. Since it's a number input, passing an empty '' won't work. Instead, I use defaultProps to set the initial value of the input as null. However, upon typing into the inp ...

How to Disable Ellipses in HTML Select on iPhones?

When using a select box with long options on mobile, the text gets cutoff with an ellipsis. This can cause confusion for users as the full text is not visible. I'm looking for a solution to either show the full text or make it wrap instead of cutting ...