Stop a looping animation keyframe in CSS and make it animate back to the beginning

I am facing an issue with a looping animation that rotates a square. Whenever I remove the class responsible for the animation, the square immediately returns to its initial position.

My objective is to animate the square back to the starting position upon triggering a JS event.

If you want to take a look at the code, here is the codepen link.

I attempted adding a transform property to the element and also changing to another keyframe animation, but unfortunately, neither approach yielded the desired result.

Below are the snippets of HTML, CSS, and jQuery code:

<div class="container">
  <div class="animate rotating"></div>
</div>
.container{
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #333;
}

.animate{
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;
  transform: all 2s ease;
}

@keyframes rotating {
  0%{transform: rotate(30deg);}
  50%{transform: rotate(-30deg);}
  100%{transform: rotate(30deg);}
}

.rotating {
  animation: rotating 6s ease-in-out infinite forwards;
  animation-delay: -2s;
}
$('.animate').click(function(){
  $(this).removeClass('rotating');
});

Answer №1

Looks like there's a slight issue in your code:

transform: all 2s ease;

You accidentally typed 'all' instead of 'transition', but I have doubts that this method will yield the desired results. If you're open to using jQuery, you can extract the current rotation and apply it to your element like this:

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { 
        var angle = 0; 
    }
    
    return (angle < 0) ? angle + 360 : angle;
}

$('.animate').click(function(){
  var el = $(this);
  var elRotate = getRotationDegrees(el);
  el.css('transform',`rotate(${elRotate}deg)`);
  el.removeClass('rotating');
  // set new transform here
});

This method will lock the current rotation of your element, allowing you to specify and transition to your desired rotation smoothly.

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 to stop a nested table from causing the parent table to expand?

This is where I'm demonstrating the issue: https://jsfiddle.net/ahnfcwdo/1/ Below is the structure of the table: table { max-width:100%; overflow: auto; } .table1 { border: 1px solid red; } .table2 { border: 1px solid blue; ...

implementing a collapsible sidebar menu with CSS tables

I am working on a layout with three columns created using css tables to perfectly fit the browser window. The first column serves as a menu and I want it to hide or move to the left when clicked, allowing the middle column to expand into its space. However ...

The jQuery UI slider is behaving strangely when rotated

Looking to create a jQuery UI Slider that operates in a 90-degree rotation. I attempted rotating and sliding, but it didn't produce the desired result. Oddly enough, when dragging horizontally, the slider moves vertically. Take a look at this interact ...

Tips for shortening your webpage for better mobile viewing

Looking to optimize my Login screen for mobile responsiveness. I am working on a project in ROR, so I have an html.erb file for the view: <body class="app flex-row align-items-center"> <div class="container"> <div class="row "> < ...

Implementing a CSS3 rotation around the center of a group following prior local rotations around the center of each individual item

My dilemma lies within a div containing numerous draggable items. When I select and group multiple items, rotating them together as a group works seamlessly – that is, unless the individual items had prior rotations applied to them. The issue arises whe ...

Why does my text keep drifting towards the left edge?

After spending a day learning CSS and HTML, I decided to recreate a website from a YouTube video and add my own customizations. I was able to center the text in my introduction successfully. However, upon reviewing my progress (see screenshot here), it is ...

CSS Scale Transformation - Font May Change Unexpectedly

When I hover over my code, the font style changes. It seems to be related to this line of code: font: 14px/1.6 "Open Sans",sans-serif;. However, I need this effect. Is there another way to achieve a similar effect (scaling to 1.2) without modifying this CS ...

Expand the accordion and incorporate both a hyperlink and an anchor tag within the content

My go-to source for codes is usually https://www.w3schools.com. They also provide an accordion feature along with the code; However, I've encountered an issue where when a link is used -> to The accordion doesn't open but remains closed. Does ...

Achieve a full vertical span of the Bootstrap 5 grid row to encompass all of its content

How can I ensure that a Bootstrap 5 grid row expands to fit its entire content vertically? Adding a label element causes the content of the first row to overlap with the second row in the example provided below. <!doctype html> <html lang="en ...

Is it possible for a DIV in one bootstrap column to appear on top of the content in another column?

Is there a way to get a div in the first bootstrap column to overflow the x-axis and have its content display above the second column to the right? <div class="row h-100"> <div class="col-3 bg-info"> <div class="LEFT ...

Struggling to designate the active button on an HTML/CSS webpage

As a beginner in the world of HTML and CSS, I'm facing some challenges with making buttons appear active. My goal is to have button1 highlighted by default when it's selected, and upon clicking on button2, the content above should change successf ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

The concept of min/max-width media query lacks grammatical coherence

I am struggling to grasp the concept of min-width and max-width media queries. If I were to create a media query, I would want it to look something like this (in pseudo-code).... if(screen.width < 420) { ApplyStyle(); } The idea of using terms l ...

DaisyUI nested collapse components featuring a dropdown menu

Here's an update following the discussion in this thread. I've implemented the solution suggested there into my Vue component, modified the collapse section, and turned it into a nested collapse with multiple collapse elements nested inside. The ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

List that scrolls with a stationary button

I am working on an interface that includes a button with a dropdown list. Here is an example: <a href="https://jsfiddle.net/DTcHh/16589/" rel="nofollow">jsfiddle</a> While the list is scrollable, I am looking to add a fixed button at the botto ...

What steps should I take to fix my responsive media query?

I am currently working on fixing some responsive issues on my WordPress website. Previously, in mobile view, it looked like this: https://i.stack.imgur.com/vpvHy.jpg After adding the following code to the CSS of my child theme: @media only screen a ...

Wordpress Sub-Menu Being Eclipsed by Banner

After upgrading my Wordpress to version 3.5.1, I noticed a problem on my site where the Submenus are loading but quickly getting hidden behind the Banner. Despite trying various modifications in the CSS file, the issue remains unresolved (and might have wo ...

Resolved issue with background image display on Mac Chrome

I'm currently in the process of developing a website that incorporates fixed background images for smooth transitions between sections. The implementation is entirely CSS-based and has been effective in all browsers except for one: Chrome on Mac (Vers ...

Ensure that each child li in the responsive dropdown menu has a width equal to the longest

Hello! I am currently working on a responsive dropdown menu and have a question regarding the width of the child li elements. Is it possible to make all the child li elements have the same width as the longest child li element? If so, what do I need to cha ...