Spin a jQuery-css animation by 90 degrees every time a button is clicked

I am facing an issue with rotating a div in my project. I have managed to partially achieve the desired functionality where pressing a button rotates the div by 90 degrees each time. However, when I try to rotate it further, the div reverts back to its original position before starting the rotation again. This restricts me from rotating it more than 90 degrees at a time. How can I solve this problem? Another question I have is why does the div only rotate once when I change 'borderSpacing' value from "-90" to "90"? After the first click, nothing happens.

JSFIddle

HTML

<div id="foo">Text</div>
<button onclick="rotateFoo()">rotate</button>

CSS

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px; 
    border-spacing: 0;
    background-color:red;
}

JS

function rotateFoo(){
    $('#foo').animate({borderSpacing: -90}, {
    step: function(now,fx) 
    {
      $(this).css('-webkit-transform','rotate('+now+'deg)'); 
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
    },'linear')

}

Answer №1

Here's a more simplified example for you to reference: https://jsfiddle.net/HwTMb/1517/

function rotateFoo(){
    var angle = ($('#foo').data('angle') + 90) || 90;
    $('#foo').css({'transform': 'rotate(' + angle + 'deg)'});
    $('#foo').data('angle', angle);
}

I'm uncertain about the necessity of using border-spacing in this scenario.

Answer №2

If you want to customize this, you can slightly modify it to suit your preferences:

DEMO

    var rotate=0;
function rotateFoo(){
    $('#foo').animate({borderSpacing: -90}, {
    step: function(now,fx) 
    {
         rotate+=2.1;
      $(this).css('-webkit-transform','rotate('+rotate+'deg)'); 
      $(this).css('-moz-transform','rotate('+rotate+'deg)');
      $(this).css('transform','rotate('+rotate+'deg)');
    },
    duration:'slow'
    },'linear')

}

function rotateFoo2(){

    $('#foo').animate({borderSpacing: -90}, {
    step: function(now,fx) 
    {
        rotate-=2.1;
      $(this).css('-webkit-transform','rotate('+rotate+'deg)'); 
      $(this).css('-moz-transform','rotate('+rotate+'deg)');
      $(this).css('transform','rotate('+rotate+'deg)');
    },
    duration:'slow'
    },'linear')

}

Incorporate the following HTML code:

<div id="foo">Text</div>
<button onclick="rotateFoo()">rotate</button>
<button onclick="rotateFoo2()">rotate</button>

To view the demonstration, please visit JSFIDDLE

For more options, consider utilizing the js library Transit

Answer №3

Although Anton made a good effort with his answer, implementing rotation in two directions requires some additional adjustments. I have provided a demonstration for this functionality: https://jsfiddle.net/abc123/

function rotateLeft(){
    var angle = ($('#element').data('angle')) || 0;
    angle -= 90;
    $('#element').css({'transform': 'rotate(' + angle + 'deg)'});
    $('#element').data('angle', angle);
}

function rotateRight(){
    var angle = ($('#element').data('angle')) || 0;
    angle += 90;
    $('#element').css({'transform': 'rotate(' + angle + 'deg)'});
    $('#element').data('angle', angle);
}

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

-=:Heading with a decorative vertical line=:-

Currently, I am working on a CSS project that requires page titles (headings) to be centered with horizontal lines positioned vertically on both sides. Additionally, there is a background image on the page which means the title's background must be tr ...

Accessing various files in a Flask application by uploading them through a consolidated button from multiple input forms

I am facing an issue with submitting multiple forms on a page using one submit button. Here is the code snippet I have implemented: <form action="" method="POST" id="form1" enctype="multipart/form-data"> <input type="file" id="for ...

Validate the email address availability using AJAX

Currently, I am in the process of creating a registration form that includes a feature to verify if an entered email address is already taken and if it is in the correct format. Here is the JavaScript code I have developed for this purpose: $('#email ...

"Troubleshooting the alignment problem in a Bootstrap 5 inline form

I am struggling to create a compact inline form on a web page featuring search filters and two buttons for submitting and resetting. Whenever I position the form fields above the buttons, they become misaligned. How can I ensure that everything stays in- ...

The color of the Angular md-switch .md-thumb is not showing up properly when switching the toggle

In Safari, the md-switch displays a yellow section on the md-thumb when toggled. However, other browsers handle the switch without any issues. The md-bar appears fine, but the md-thumb is yellow. I have tried setting everything to the blue color I am using ...

Instructions on storing information on a distant server using a mobile application (jqm+phonegap)

Currently working on building an application with jqm and phonegap. The app requires users to input certain parameters and generate results based on those inputs. After the calculation is complete, I would like the user to be able to save all the data, i ...

Retrieving the value of an input tag within dynamically created table rows using JSP

I have encountered an issue where I am only able to fetch the value of the input tag with the id b_quantity field from the first row, even though each row in the table contains a different record. My goal is to target the value of b_quantity in the same ro ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

Combine various jQuery addClass functions into a single function

Is there a way to combine the following code into one function? (I'm new to jQuery) <script type="text/javascript> $('.job:has(.active)').addClass('active'); $('.employers:has(.active)').addClass('active ...

Guide to creating a PHP loop in the footer of a Magento website

Hey Developers! I have been using the following commands in footer.phtml to retrieve all my cms/blocks in the Magento's footer. <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('home')->toHtml() ...

The success callback function in jQuery.ajax() sometimes receives undefined parameters

In my current code, I am using an ajax call to communicate with a Wordpress file responsible for creating WP users. jQuery.ajax({ method: 'POST', dataType: 'json', url: ajax_object.ajax_url, // Post ...

Are you seeking to conduct a long-polling poll with a connectionToken in Visual Studio 2015?

In my current Visual Studio 2015 debug mode session, I noticed that there is a repeated call being made (something I have never experienced with Visual Studio 2012). https://i.sstatic.net/ETvon.png Upon further inspection, I discovered that the call is r ...

Prevent elements from overlapping within a flexbox container

I've encountered an issue with resizing the window causing the logos to overlap the portrait image. Is there a way to fix the logos relative to the portrait? Below is the code: /* Defaults for Main Part of Pages */ body, div, h1, p { margin: 0; ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

Purge the external CSS files

Scenario In my React Router setup, most pages include their own .css files along with the default antd (UI framework) stylesheet: import '../styles.css'; This ensures that all components inherit these styles automatically. Issue at Hand Now, I ...

Two divs featuring a cohesive gradient background, with one div containing a sticky element

I am currently facing a dilemma that is causing me some frustration. The situation is as follows: I have two divs on my webpage. The top div consists of a banner with the logo, while the bottom div is the navbar containing icons as links and a dropdown me ...

unique hyperlink to an external style sheet

element, I came across this line in the header of a web page that was generated by a program. Any thoughts on what significance the number and ID serve in this stylesheet link? <link rel="stylesheet" type="text/css" href="css/contact.css?4131768016" ...

How can I make a sticky element appear behind a different element?

https://jsfiddle.net/30suam6z/1/ .first { height: 100vh; background-color: red; position: relative; z-index: 2; /* Increase z-index to ensure it covers .test */ } .second { height: 100vh; background-color: yellow; position: relative; z- ...

Creating consistent div sizes for varying image and title lengths in bootstrap

In my angular project, I am receiving data in the form of image, title, and location. Despite my efforts to create a responsive div, I have been unsuccessful in achieving uniform sizes. <div *ngFor="let company of companies" class=" ...

Using both CakePHP and jQuery to create a semicircle chart

I need a pie chart that visually represents two dynamic values. When the red value is 90%, the pie chart should be filled with red color up to 90% and the remaining 10% should be filled with green color. I also require the pointer to change dynamically b ...