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

Ensuring grid columns are equal for varying text sizes

I am looking to achieve equal width and spacing for columns without using the width, min-width, max-width properties. Can anyone help me accomplish this using flex or any other method? .d-flex { display: flex; } .d-flex .col { margin: 5px; ...

Initiating an AJAX request to communicate with a Node.js server

Recently, I started exploring NodeJS and decided to utilize the npm spotcrime package for retrieving crime data based on user input location through an ajax call triggered by a button click. The npm documentation provides the following code snippet for usi ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

- **Rewrite** this text to be unique:- **Bold

Check out this relevant jsFiddle link Below is a list where I aim to make all occurrences of the word 'Bold' bold: <ul id = "list"> <li>Make this word Bold</li> <li>Bold this as well</li> <ul> ...

The transitionend event fails to trigger if there is no active transition taking place

Take a look at this: http://jsfiddle.net/jqs4yy0p/ JS $('div').addClass('switch').on('transitionend', function(e){ alert('end'); }); CSS div { background-color: red; /*transition: background-colo ...

Utilize jQueryUI sortable to serialize a list item within an unordered list

I'm looking to learn how to generate a JSON or serialize from a ul element with nested list items. Here's an example: <ul class="menu send ui-sortable"> <li id="pageid_1" class="ui-sortable-handle">Inscription <ul class="menu ...

AJAX and Java combination causing issues with logging out in the system

I am working with AJAX using jQuery to trigger a function when clicking a link with the ID logOut. Here is the AJAX code: $("#logOut").click(function(){ $.ajax({ url: "Logout" }); }); This AJAX function calls my Java Servlet shown below: /** ...

Is it possible to incorporate an external javascript file in my CSS file?

Currently, I am attempting to create a setup where my background adjusts based on the width of the user's browser. However, I am constrained by a background specified in the external stylesheet under a specific element. While I have the ability to alt ...

What are the best practices for utilizing the onLeave() function in fullpage.js?

My goal is to make the user scroll through 4 sections. Upon reaching the fourth section, if the user scrolls down again, instead of going to the fifth section, the view should loop back to the first section. (The fifth section only contains the imprint and ...

Adding an HTML element to the DOM in an AngularJS directive without using jQuery

Looking to enhance my AngularJS directive by including an svg tag within the current element, currently using jQuery for this purpose. link: function (scope, iElement, iAttrs) { var svgTag = $('<svg width="600" height="100" class="svg">< ...

I am experiencing issues with a few of my design choices not functioning correctly

I am facing issues with some of my styles. I have put in a lot of effort, but there seems to be a problem with my menu. The last part of my CSS is not functioning correctly. When hovering over the menu content, I want it to turn black and... #site_menu { ...

Transferring data via AJAX technology

My goal is to empower the ability to upload files using AJAX. I attempted to utilize (JavaScript) in this manner: $("input[type='file']").change(function(){ var file = document.getElementById("uploadelement").files[0]; $.ajax ...

Updating a table without the need for a button in PHP and AJAX with an Excel-inspired approach

I'm facing a scenario where I need to dynamically update the contents of a table row. To achieve this, I want the cell to transform into a text box when clicked. Here's how I implemented it: <td contenteditable></td> After making ch ...

Issue with responsive design: Media queries not applying max-width

GOAL I want the content of my page to adjust to screen sizes that are smaller than 600px wide. ISSUE When using the responsive tool in Chrome, preset screen sizes like iPhone X do not apply media queries properly. Even manually adjusting the screen size ...

Is there a way to retrieve a specific section of a webpage using an AJAX GET request?

When making a GET request to the server, we can retrieve an entire page. However, what if I only need the content of a specific div on that page? Do I have to fetch the entire page and then use jQuery's find() method to extract the div content? Or is ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Having trouble with Bootstrap v4 dropdown menu functionality?

For some reason, I cannot get the dropdown menu to work in my Bootstrap v4 implementation. I have tried copying and pasting the code directly from the documentation, as well as testing out examples from other sources on separate pages with no luck. &l ...

Can divs be arranged in a similar fashion as images?

My goal is to create a navigation bar (#nav) with each nav item being a div (#nav div). However, my current approach isn't working as expected. Here is the code I'm using: #nav { background: url("navbg.png"); /* navbg.png is 1x40 pixels */ ...

Reduce code length for generating DOM fragment with jQuery

I'm currently working on generating a tree of elements that will be used as an input for JsTestDriver unit tests. I've got some code to create this tree which involves using Document Object Model methods in JavaScript. I'm wondering if there ...

Having trouble retrieving the Post value ID from row table in PHP using Jquery

Although I have searched extensively for a solution to my problem, none of the suggested fixes seem to work for me. The issue is quite simple - I need to retrieve the item-id value and then POST it to del.php. However, I am unable to access the POST value ...