How can you trigger CSS transitions to happen multiple times?

Currently, I have a basic circular logo that rotates 360 degrees when certain ajax functions are triggered.

While this works as intended, the rotation only occurs once after the function is triggered, and I need to reload the page for it to happen again.

How can I ensure that the rotation happens every time the spin_logo() function is activated?

ROTATION FUNCTION

function spin_logo(){

    var n = 360;
    $('.logo').css({
        transform:'rotate('+n+'deg)',
        '-ms-transform':'rotate('+n+'deg)',
        '-moz-transform':'rotate('+n+'deg)',
        '-o-transform':'rotate('+n+'deg)',
        transition: '1s linear',
        '-ms-transition':'1s linear',
        '-moz-transition':'1s linear',
        '-o-transition':'1s linear'            
    });
    n+=360;

}

ROTATION USE CASE

The spin_logo() function is called right after the success function.

$(document).on('click touchstart', '.publish', function(event){
    event.preventDefault();
    var $this = $(this);

        $.ajax({
             type: "POST",
             url: base_url + "post/publish",
             dataType: "text",  
             data: {
                title: $('.title').html(),
                sub: $('.sub-title').html(),
                txt: $('.editor').html(),
                cat_str: $('#cat-drop').val(),
                str: window.location.pathname.split('/').pop()
             },
             cache:false,
             success: 
              function(data){
                spin_logo();
                $('.response-info').slideToggle(500);
                $('.response-info').html(data).fadeIn(500);   
                setTimeout(function(){
                    $('.response-info').slideToggle(1000);
                }, 10000);    
            }       

         });                

    return false;
});

Appreciate any help on this matter.

Answer №1

The issue arises from the fact that 'rotate(360deg)' is equivalent to 'rotate(720deg)'. As browsers calculate degrees modulo 360, the transform property remains unchanged after the initial transition, resulting in no visible change.

To rectify this, you must remove the transform once the animation is complete. This can be accomplished by utilizing the transitionEnd event. To observe it in action, refer to this live example: http://jsfiddle.net/8rXMw

var $logo = $('.logo');
$logo.on('transitionend', function() {
   $logo.removeClass('rotated');
});

$('#button').on('click', function() {
$logo.addClass('rotated');
});

This code snippet adds the rotated class to the div, triggering the transform and animation. Once the transition concludes, the transitionEnd event triggers, leading to the removal of the class. Consequently, the div reverts to rotate(0) sans any transition. Upon clicking the button anew, the process repeats itself.

Note that 'transitionEnd' may require prefixes in certain browsers for full support.

Answer №2

To simplify this process, consider using CSS for animation and jQuery to handle adding and removing classes.

Check out an example here

.animate {
    -webkit-animation: rotate 2s infinite linear forwards;
}
@-webkit-keyframes rotate {
    0% {
        -webkit-transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
    }
}

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

PHP error caused by an issue with AJAX JSON Parser

I'm facing a JSON parser error in my code. The Ajax call never reaches the 'done' state. Can someone assist me with this issue? <input type="submit" class="button" name="insert" value="load"/> <div id="wines"> <!-- Data w ...

Exploring JavaFX and FXML TreeTableView customization for column and header styles

I've been working on a JavaFX project and I'm having trouble customizing the style of the TreeTableView header or columns, like changing the color, width, font size, etc. I've tried using various codes like these but none seem to work. ...

Unable to trigger jQuery .click event

Having recently delved into the world of AJAX, jQuery, and JavaScript, I am facing a challenge that I believe is rooted in a simple oversight on my part. Expressing this issue can be quite perplexing, but I'll do my utmost to articulate it clearly. I ...

Launch Bootstrap modal when clicking on an Iframe

I'm currently working on implementing a button that triggers a modal with an iframe inside. The goal is for the iframe to load only when the modal is opened. However, upon clicking the button to open the modal, nothing loads and there are no error mes ...

Insert a Facebook like button

I am trying to dynamically append a Facebook like button to a specific div using dynamic URLs. For an example of how this can be done, please refer to this simple demonstration: JsFiddle After attempting to insert the code within an ajax call, I encounter ...

The use of the jQuery clone() method in conjunction with jQuery TABS allows for the display of cloned fields

I've implemented jQuery tabs with the following code structure: <ul class="tabNavigation" id="tabs"> <li><a href="#AAA">AA</a></li> <li><a href="#BBB">BBB</a></li> </ul> ...

Issues with loading CSS, JavaScript, and links when deploying a Spring Boot application as a WAR file in Tomcat

My Spring boot web application runs smoothly as an executable jar, but when I build it as a war and deploy it to Tomcat, the CSS and JS files fail to load. Upon further investigation, I discovered that all links are pointing to the root context path "/" I ...

Why isn't the content of the initial tab in a <section> shown when clicking a link in the side-drawer?

View the JSFiddle here. Within this MCVC, a side drawer is implemented (opened by clicking the top left button) that contains three labeled links: Link One, Link Two, and Link Three. Each link has an href attribute value that starts with "#" concatenated ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

Creating a customized tooltip without the need for calling $(document).foundation() and using modernizr

I'm facing an issue with initializing the foundation tool-tip without having to initialize everything (such as $(document).foundation()). It seems like a simple task, but I am struggling. I have two questions in mind: (1) How can I utilize new Founda ...

Error validation for jQuery div dropdown

Can jQuery validation be used to set the required attribute on a Bootstrap styled div dropdown instead of an option/select tag? The tags cannot be changed on this page, and there are multiple div dropdowns. <div class="btn-group"> <button typ ...

Having trouble accessing and setting the values of a JSON array retrieved using $.get method in JavaScript outside of the function

Executing the following code snippet results in the desired values being displayed in console.log: var q; $.get('/ajax_subscribers', { code: 'qyhskkcnd'}, function(returnedData){ q = returne ...

I'm having trouble getting the data to parse correctly in ajax. Can anyone explain why it's not working?

I have implemented a system where an excel file is uploaded using AJAX, and information about the success or failure of the upload is sent from the upload page to the PHP page using json_encode. However, I am facing an issue with accessing this data indivi ...

Different methods to incorporate Glyphicons without relying on Bootstrap CSS

For a recent client project, I utilized basic HTML and CSS. However, the client expressed a desire for Glyphicons to be included in the website menus. Attempting to incorporate Glyphicons with Bootstrap CSS posed challenges as it affected other aspects of ...

Users using an iPhone are unable to adjust the scale or scroll on this website

I find myself wondering what I might be overlooking in this situation Here is the HTML code: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="../../nImg/favicon.ico" ...

Using jQuery to handle nested div elements and triggering a click event only once when the inner div is clicked

I have a situation where I have nested divs. When the inner div (closeme) is clicked, I do not want the click event of the outer div (container) to be triggered. How can I achieve this? html <div id="container"> content <div id="closeme">< ...

Is it possible to enlarge the window screen using css?

After using zoom at 90%, everything was working fine until we introduced high charts. The hovering property doesn't display in the correct position. Looking for a solution to show a zoomed window on a small screen, like a laptop screen. Does anyone h ...

Explore the versatility of jQuery by utilizing multiple objects in your POST and GET requests to PHP for enhanced

I am trying to send multiple arrays to a PHP page using jQuery and retrieve results, but I am encountering an issue where the array values are not being properly passed to the PHP page. Notice: Undefined index: $name Notice: Undefined index: $type Notice ...

Unable to Utilize Custom Colors in Tailwind CSS within NextJS

I am currently experimenting with NextJs and Tailwinds CSS for a new project. However, I keep encountering an error when attempting to apply a custom background color: Failed to compile ./styles/globals.css:7:12 Syntax error: /Users/anishkunapareddy/Deskto ...

Touch Screen Button Interaction

Planning to create a Kiosk website with HTML5 that includes point and drag & drop functionality. The site will have buttons and images for user interaction, with actions triggered by finger touches on the screen instead of mouse clicks. Would it be more ...