Spinning Divs with JQuery

I have successfully rotated a div using the following code snippet:

function AnimateRotate(d){
    var elem = $("#arrow");

    $({deg: 0}).animate({deg: d}, {
        duration: 200,
        step: function(now){
            elem.css({
                transform: "rotate(" + now + "deg)"
            });
        }
    });
}

Now, I am encountering an issue when attempting to rotate the div back in the opposite direction. After the div has been rotated and I click on it again, it just repeats the same cycle of animation and ends up at its original position. However, my intention is for it to perform the same rotation but in the reverse direction.

To better illustrate my point, I have provided a link to a JSfiddle.

Visual representation:

Answer №1

Consider a scenario like this: verify if the dropdown container is visible and execute a function with varying parameters.

$( ".panel-heading" ).click(function() {
  var isVisible = $("#recipe-container").css("display");
if (isVisible == "block") {
    AnimateRotate(0, 90);
}  
else { 
AnimateRotate(90, 0);
}
$("#recipe-container").slideToggle();
});

function AnimateRotate(d,g){
var elem = $("#arrow");

$({deg: g}).animate({deg: d}, {
    duration: 200,
    step: function(now){
        elem.css({
            transform: "rotate(" + now + "deg)"
        });
    }
});
}

JsFiddle: http://jsfiddle.net/78DCU/1/

Answer №2

Instead of relying on jQuery for the animations, I took a different approach and used CSS to control them.

By assigning the class 'container--open' to the main container, you can then apply styles to its child elements.

.container--open #recipe-container {
    opacity: 1;

    -webkit-transform: translateY(0);
       -moz-transform: translateY(0);
            transform: translateY(0);
}

.container--open #arrow {
    -webkit-transform: rotate(90deg);
       -moz-transform: rotate(90deg);
            transform: rotate(90deg);
}

This simplifies your jQuery code to:

var container = $('#container'),
    trigger   = $('.panel-heading');

trigger.on('click', function() {
    container.toggleClass('container--open');
});

Check out the demo here: http://example.com/demo

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

Why is the jQuery not functioning within the AngularJS function?

I am encountering an issue with writing jQuery inside an AngularJS function. I can't seem to figure out why it's not working properly. HTML <div> <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showD ...

Trying to update the +/- icon on an accordion dropdown, however, the local HTML file is not loading the JavaScript file. (Using Bootstrap 4)

I'm completely new to JS and struggling a bit, so please be patient. I've been searching online for a few days now without much luck. I'm using Bootstrap 4 and trying to create an accordion with a +/- icon that changes when expanded or colla ...

When an image is added, it will display against a backdrop of pure white

Hey there, I have a question regarding an image on my website. I removed the background using PowerPoint, but when I upload it, there is still a white background around it. Even changing the background color doesn't remove the white outline. Any tips ...

Is there a way to specify the login response details when making an Angular API request?

I am currently using Angular to connect to my backend login service. However, I am facing an issue with setting the popup message when the username or password is incorrect. I want to display the detailed message from the API on my login page when any erro ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

Restrict the display of items in a unordered list element

Below is my code snippet that limits the number of visible list items in a ul: $wnd.$(el) .find('li:gt(9)') .hide() .end() .append( $wnd.$('<li>+More</li>').click( function(){ $wnd.$(this).nextAl ...

Babel is failing to transpile the Modal component from material-ui-next to ES5

Issue with Babel transpiling Modal component from material-ui-next Here is my .babelrc configuration: { "presets": ["es2015", "react", "stage-1", "stage-2", "stage-3"] } This is the webpack-config.js setup: var webpack = require('webpack'); ...

Troubleshooting problem with jQuery attribute value assignment

I am currently working with text boxes that store data in local storage upon saving. $(".formFieldUserData").each(function () { var key = $(this).attr("name"); var value = $(this).attr("value"); localStorage.setItem(key, value); } However, I have c ...

Error in syntax for jQuery's .find() method

Is there a mistake that's preventing the results from showing up? When I delete the code between the "FROM HERE" and "TO HERE" comments, everything seems to work fine (at least it shows up on screen). I have a feeling that the issue lies with the .fi ...

PHP side is rejecting the data that is being transferred via AJAX GET request

var myData = 'username='+j; //constructing a post data structure alert(myData); jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response1.php", //The location for Ajax calls dataType:"text", // Data fo ...

"Troubleshooting: Why is Angular's Equalizer from Foundation not

I'm having trouble getting Foundation Equalizer (the JS tool for equalizing div heights) to function properly. The demo is not displaying correctly. I am currently using Foundation v6.1.2 My setup includes using it in an ng-view, and in the index fi ...

Is it feasible to activate a Bootstrap Tooltip from a different element?

I am currently developing a system that enables users to add notes over an image they upload. Presently, I have a note div that, upon clicking, opens a text box for editing. When hovering over this div, I utilize Bootstrap Tooltip to preview the contents o ...

What is the process for including parameters in a javascript/jquery function?

This unique script enables you to click on a specific element without any consequences, but as soon as you click anywhere else, it triggers a fade-out effect on something else. Within the following code snippet, you can interact with elements inside $(&apo ...

Creating beautifully formatted HTML text in a PDF document using JavaFX and iText

Can you convert a styled HTML text (with color, alignment, etc.) from an editor like HTMLEditor to an editable PDF using iText? I've searched online but couldn't find any information on this. Appreciate any help. Thank you. ...

The Express Electron framework does not support importing local JavaScript files

Despite my extensive search before flagging this as a duplicate, I have not been able to find the solution I need. I am encountering issues with using express and electron. Everything runs smoothly when I execute npm start (the start script in package.jso ...

Disable the mousedown event in JavaScript/jQuery

During a drag and drop operation, I have set certain limits on the screen. When the draggable object passes these limits, I want it to return to its original position. The issue I am facing is that if the onmousedown event is active, the object does not r ...

How can AJAX be used to execute a PHP script that deletes a record from a database table?

Yesterday, I asked for help on how to save user-generated blog posts and I successfully tackled the database aspect of it. Now, my next goal is to be able to delete a blog post upon clicking a button with an onclick event. After researching extensively onl ...

Transmit a basic JSON object from a Node.js server to an index.html webpage

People often overlook this seemingly simple solution when I search for it on Google. My goal is to send a basic json message or file to my index.html page. Here's the Node.js code: const express = require('express'); const app = express(); ...

Increased spacing HTML

Trying to create a footer in HTML, but each time I attempt it ends up with an extra margin on the left side. Here is my current footer code: <div id="footer"> Tester </div> #footer { background-image: url(images/backgroundrpatternf ...

Excessive width of the lower border

I have a dropdown menu on my website and I wanted to add a border-bottom to the menu. However, the border appears too wide. I went through every step of this solution as it seemed like the same problem, but nothing seems to be working. It would be great i ...