When I click on the icon, I wish for it to revert back to its original state by spinning

Is there a way to revert the icons back to their original state when clicked again, without losing any of the current functionalities?

  1. When an icon is clicked for the first time, it rotates 180 degrees.

  2. The icon rotates back if another icon is clicked or if the click is outside the icon.

In addition to these features, I would like to introduce a new feature where clicking on an already rotated icon will spin it back to its original position.

function rotate(e){
  resetRotation();
  document.getElementById("me").className="spinner in fa fa-caret-down";
  e.stopPropagation();
}

function resetRotation(){
  document.getElementById("me").className="spinner out fa fa-caret-down";
  document.getElementById("you").className="spinner out fa fa-caret-down";
}

function rotatea(e){
  resetRotation();
  document.getElementById("you").className="spinner in fa fa-caret-down";
  e.stopPropagation();
}

document.addEventListener('click', resetRotation);
.spinner {
  transition: all 0.5s linear;
}

.spinner.in{
  transform: rotate(180deg);
}
.spinner.out{
  transform: rotate(0deg);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<i onclick="rotate(event)" id="me" class="spinner fa fa-caret-down "></i>
<i onclick="rotatea(event)" id="you" class="spinner fa fa-caret-down"></i>

Answer №1

    let hasChanged = true;
    function rotateElement(event){

      document.getElementById("me").className = "spinner fa fa-caret-down" + (hasChanged ? "in" : "out");

      hasChanged = !hasChanged;

      event.stopPropagation();
    }

You can also apply the same logic for rotating element 'a'

Answer №2

Make sure you have added the in class to your i tag for it to rotate back and exit the function. To verify if an element already has a class, you can use the following code:

document.querySelector("#you").classList.contains("in")
function rotate(e) {
  // Check if already rotated and return
  if (document.querySelector("#me").classList.contains("in")) {
    resetRotation();
    return;
  }
  resetRotation();
  document.getElementById("me").className = "spinner in fa fa-caret-down";
  e.stopPropagation();
}

function resetRotation() {
  document.getElementById("me").className = "spinner out fa fa-caret-down";
  document.getElementById("you").className = "spinner out fa fa-caret-down";
}

function rotatea(e) {
  // Check if already rotated and return
  if (document.querySelector("#you").classList.contains("in")) {
    resetRotation();
    return;
  }
  resetRotation();
  document.getElementById("you").className = "spinner in fa fa-caret-down";
  e.stopPropagation();
}

document.addEventListener('click', resetRotation);
.spinner {
  transition: all 0.5s linear;
}
.spinner.in {
  transform: rotate(180deg);
}
.spinner.out {
  transform: rotate(0deg);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<div style="padding:20px;">
  <i onclick="rotate(event)" id="me" class="spinner fa fa-caret-down "></i>
  <i onclick="rotatea(event)" id="you" class="spinner fa fa-caret-down"></i>
</div>

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

What is the best way to retrieve the page slug within the layout file in Next.js, specifically when using the app folder structure?

In my latest project, I have implemented a nested layout using the new app folder. Within this layout, I have included a header that appears across all pages in the path www.mysite.com/some-slug. One issue I am facing is with the signup button located in t ...

Understanding the functionality of the Array.prototype.map() method when used with JavaScript Objects

Experimenting with code: let obj ={}; let newItems = ["Apple", "Banana", "Carrot", "Donut"].map(item => { obj.count= Math.random()*item.length; obj.itemName= item; return obj; }); console.log(newItems); The output ...

Following the completion of every asynchronous operation, a callback will be executed

I am facing a situation where I have an array of images that are uploaded with a series of asynchronous operations as shown below: for ( let key in imageFileObject ) { const imageFile = imageFileObject[key] dispatch('get_signed_request', ima ...

Typescript: Error encountered. Invalid input: Non-string value provided to `ts.resolveTypeReferenceDirective`

A while back, I developed an npm command line application that was working perfectly fine. However, after a recent update due to changes in TypeScript versions over time, I encountered an error when trying to run the package. The error message I received w ...

Head and tail tally

I've been working on coding a heads or tails system in JavaScript, but I've hit a roadblock. I am struggling to find a solution. Here is what I have so far: const userInput = prompt("Heads or Tails?"); const arr = [0, 0, 1, 1, 1, 0, 1, 0, 1]; ...

What is the best way to handle a form with nested components in React?

I have successfully developed a form that changes dynamically, incorporating my own components. However, I am facing the challenge of extracting information from this form because the select tag exists only in the children components. After some research, ...

Can JOLT be utilized to convert this HTML into a JSON output?

Is it possible to transform this HTML into JSON using JOLT SPEC? [<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <HEAD> </HEAD> <BODY><br> #Message Receive correctly<br> ORDERID=1725786449 ...

Updating a table in Javascript after deleting a specific row

Is there a way to automatically reindex rows in a table after deleting a row? For example, if I delete row 1, can the remaining rows be reordered so that they are numbered sequentially? function reindexRows(tableID) { try { var t ...

Exploring ways to utilize array.find by comparing it to a different object

There are two arrays in JavaScript named designs and articles. var designs = [ { design_id:"bwbmbqlujurv", article_id:14782, name:"adidas demogorgon black" }, { design_id:"lg9yba2gkcwr", article_id:14782, name:"harry potter w ...

What is the best way to conduct testing on a component that utilizes destructured props?

I have been working on testing a form that I created using React and Material UI. The form includes destructured props within an arrow function component that I am having trouble testing. How can I work around this issue? I attempted to use Jest with Enzy ...

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

PHP comment form failing to process complete field inputs

Having some issues with a PHP comment form on my website. It's not sending all the inputted information from the fields. Any help would be greatly appreciated. This is the HTML code I'm using: <form method="post" action="assets/php/mail.php" ...

Using jquery, transform json data into html table format

As a beginner in the realm of coding, I am currently experimenting with extracting data from my json file and transforming it into an HTML table. My tool of choice is the Atom code editor, and I am attempting to use JavaScript, specifically jQuery, to it ...

Designing a straightforward thumbs-up icon

Hey there! I'm currently working on a blog application and trying to set up a simple like button for each post identified by its primary key (pk). However, I encountered an error along the way. The error message I received is "NoReverseMatch at /sing ...

Attempting to isolate just a fragment of the inner content

Option Explicit Sub VBAWebscraping2() Dim IEObject As Object Set IEObject = New InternetExplorer IEObject.Visible = True IEObject.navigate url:="https://streeteasy.com/building/" & Cells(2, 4).Value ...

The bubble dialogue box in my picture

Looking to create a panel with images that, when clicked on, display an info window similar to Google Map's pin maker. When you click on an image, a balloon should appear containing additional information. Check out this example <a id="infowindow ...

Creating a modal using JavaScript and CSS

When I click on the hello (plane geometry) as shown in the figure, a popup appears on the extreme left of the screen instead of appearing on the plane geometry box. Can someone please help me fix this issue? I have also included the code below: https://i. ...

Utilizing setInterval in Vue 3 to efficiently eliminate elements from an array

I am looking to implement a straightforward Snackbar using VUE 3. While I had no trouble doing this in Vue 2, Vue 3 seems to have some nuances. Currently, I have stored the messages array in the Vuex store as shown below: import { createStore } from &apos ...

What are the advantages of using clearfix for clearing floats in CSS?

Recently, I encountered an issue with using clearfix to clear the floating effect in CSS. Someone mentioned that it may not be the best technique and suggested using alternative methods. Is this information accurate? If so, what are some other options tha ...

unable to pre-select default option

My dynamic options select is functioning correctly, adding the selected attribute to a specific option with an id value. However, I am encountering an issue where even with an option that has the selected attribute, the first option is always displayed as ...