What are the limitations of using a CSS transition alongside a separate animation created with jQuery's animate method?

I am facing an issue with moving and flipping a button simultaneously when clicked. I have set up two animations to happen at the same time, each with the same duration. However, only the CSS scale transform seems to be working while using both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works perfectly.

// identifying elements
var button = $("button");

// handling click event
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });
  
// the problem: the following animation is not visible
  button.animate({
    "top": "-100px" // I even tried without "px"
  }, 0.15 * 1000);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  
  position: relative;
  transition: all 0.15s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Hello World</p>
  <button>Click me</button>
</div>

The JSFiddle illustrating this issue can be found here.

Appreciate any help on this matter.

Answer №1

Optimize your transition property by using only the necessary values, such as transform 0.15s instead of all 0.15s

// locate elements
var button = $("button");

// click event handling
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

  // bug: animation won't show
  button.animate({
    "top": "-100px"
  }, 0.15 * 1000);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: absolute;
  transition: transform 0.15s; /* updated */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Hello Universe</p>
  <button>Press Here</button>
</div>

Answer №2

While defining your button style with transition: all 0.15s;, keep in mind that it will impact the top property as well. Consequently, the top animation occurs shortly after the CSS manipulation and each step of the top animation undergoes a transition.

  1. The top animation occurs slightly after the CSS manipulation.
  2. Each step of the top animation experiences a transition effect.

This situation creates a potential racing condition where the top animation might go unnoticed due to the rapid pace of transitions. Furthermore, jQuery's animation also incorporates an easing effect over every step.

If no easing function is specified when using $.fn.animate, it defaults to swing, defined as:

 function( p ) {
    return 0.5 - Math.cos( p * Math.PI ) / 2;
 }

Here, the parameter p ranges from 0 to 1.

In this scenario, you are instructing jQuery to change the top property from 0 to -100 over 150ms. Typically, the animation interval is about 13ms, but for simplicity, we assume it to be precisely 15ms resulting in 10 animation steps. With the swing easing, the first step computes to:

 100 * (0.5 -  Math.cos( (0.1 * Math.PI ) / 2) = 2.45

To summarize, by utilizing transition: all 0.15s and disregarding the race condition, clicking the button would horizontally scale down to 0 and move upwards by 2.45px within a duration of 0.15s.

Alternatively, by solely transitioning the transform property while leaving the top transition to jQuery, you can observe both animations occurring simultaneously.

In the provided code snippet, I extended the time frame to 1s, introduced console statements at each stage, and featured multiple buttons – one with regular button styles, another transitioning only transform, and a third transitioning both transform and top without using jQuery animations.

(previously included JavaScript and CSS code snippets)

Answer №4

Make sure to set your button position to absolute!

var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

    // there is a bug: the animation below is not visible
  button.animate({top: "-100px"}, 0.15 * 1000);
});
button{
  position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Hello World</p>
  <button>Click me</button>
</div>

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

Tips for properly showcasing images on a webpage after ensuring all other content has loaded

Is there a way to have an image load last on a webpage after all other content has been loaded? I have an image that is retrieved from a database when a button is pressed, but I would prefer for the entire page to load first and then display the image. C ...

Issue with passing parameters through AJAX setTimeout causing it to not function as expected

When the user inputs something, a program uses ajax to output something back. This process generally works well, but there is an issue with passing variables as parameters to a remote function from a script. The problem arises when using the setTimeout fu ...

Passing state and handlers down through nested React components: A guide

I'm encountering an issue when trying to pass handlers down through my React components. I've attempted to follow the guidance provided in the Lifting State Up section of the React documentation. The concept involves having a Page with tabbed n ...

`the mobile site is not displaying properly on the screen`

I'm struggling to make my website responsive on mobile devices. I'm using Bootstrap, but when viewed on a mobile device, it's not adjusting the layout properly. Other sites I've worked on automatically zoom in to display correctly on mo ...

Unlocking the potential of NextAuth.js by enhancing the user session with additional database information on authentication

Currently, I am in the process of creating a straightforward credentials sign flow using next-auth ^4.24.5 with a nextjs 14 app. Within my user model, there is a boolean property named 'isAdmin' that I wish to make accessible in my session using ...

creating a custom Django template filter that takes a variable as an argument

Utilizing a custom Django template filter, I have set up a mechanism to access elements in a 3D array within my template. The 3D array, swipeData, is passed from views.py to index.html. In index.html: function getNearestHalfHourTimeString() { var now ...

What's the best way to make sure a div container fills in the remaining space between elements?

How can I make the center div take up the remaining space between the left and right divs, without covering them? The contents in the center can overflow hidden if necessary. View my code on jsFiddle HTML <div id=container> <div id=left> ...

Issue with AJAX form submission selecting an incorrect row among dynamically generated rows of data

Currently, I am fetching data from a database and displaying it in a table. One column includes the ID of each row, which I then pass to a modal using the following code snippet: <a href=".user_id<?php echo $row['id']; ?>" ...

Next.js displays component twice

When examining the first image, it appears that Next.js rendered this element twice. Initially, I suspected the issue was related to the tables I used. However, even after removing the tables and replacing them with just , the element still renders twice, ...

Issues with Vue Router functionality in Leaflet Popup are causing unexpected behavior

Incorporating Leaflet and Vue together in my codebase using the vue2-leaflet wrapper has presented a challenge. Specifically, I am facing difficulties getting Vue $router to function within Leaflet's popup. Below is a snippet of my current code along ...

What is the process for using JQuery to switch the class of an element to 'nested-class'?

Styling with CSS: #logo-container { position: fixed; right:5px; .home-page { /* homepage styling */ } .content-page { /* Modify the $element's class to this class */ margin-top: 78px; } } Using JQuery to change the class of #lo ...

Breaking apart a mesh using THREE.js

Can a single THREE.Mesh be divided into multiple meshes? For instance, can a mesh with 2,000,000 polygons be split into 2,000 meshes each with 1,000 polygons? Edit: Realistically, it may not be possible to retain the exact same number of polygons/vertice ...

A collection of JSON objects retrieved from a fetch request

When I send a fetch request to an API, I receive a response that is an array of JSON objects, for example: [ {"key":"val", "k2":"v2"}, {"k3":"v3", "k4":"v4"} ] Currently, I am handling this by using response => response.text() Is there a more efficie ...

Resizing Images in a Responsive Design

When creating a website, have you considered options besides resizing images for mobile devices? Instead of downloading the full image and resizing it to fit the screen, causing strain on CPU and RAM, are there alternative methods that could be more effi ...

Utilizing Bootstrap Tooltips in an Electron App

I am currently using Bootstrap alongside Electron, and I have encountered an issue with the tooltip functionality. Interestingly, when I view the page in a regular web browser like Chrome, the tooltips function as expected. However, when I open the page in ...

Tips for setting HTML content in a text field using SOAP API in Tuleap

We are using the Tracker SOAP API to create fresh tracker artifacts. While making changes to an artifact in Tuleap, there is an option to choose between plain text and html in a dropdown menu for a text field. Our goal is to input html-formatted text into ...

When previewing a card on Twitter's validator tool, the image displays properly. However, when attempting to share the image on

Below is the code that I have written on my HTML page: <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@name" /> <meta name="twitter:title" content="Twitter - image share" /> <meta name="twi ...

The AngularJS plugin "chosen" is experiencing issues with the "chosen:updated" feature, despite functioning

After successfully integrating the selected plugin into my AngularJS app, my app.js file now has the following code: myApp.directive('chosen', function() { var linker = function (scope, element, attr) { scope.$watch('countriesL ...

Validating form inputs with jQuery in a Flask application

Utilizing wtforms in my Flask application, I am interested in validating forms in the browser using jQuery. Here is a snippet of my form code: class LoginForm(Form): email = StringField('Email',[validators.DataRequired(message='Sorry, t ...

Having difficulty modifying the width of the BODY element using CSS

For my webpage, I want the body to have a silver background that fills only 75% of the page. This means that only 75% of the page will be painted silver, while the remaining part will be left unused and painted according to the browser's defaults. The ...