Does the addClass() method run asynchronously?

When trying to remove the class transition (and therefore, the CSS transition property), moving the div to 200px immediately, reapplying the transition css property, and then animating the div to the right over 1 second, it appears to be frozen instead.

It seems like applying the css left property is taking longer than removing the transition class. Could addClass() be asynchronous?

var elem = $('#elem');

elem.removeClass('transition');
elem.css('left', 200);
elem.addClass('transition');
elem.css('left', 0);
#container {
  position: relative;
  width: 400px;
  height: 200px;
  background-color: red;
}
#elem {
  width: 50px;
  height: 50px;
  position: relative;
  left: 0;
  top: 0;
  background-color: blue;
}
.transition.linear.scritta {
  -webkit-transition: all 1.0s linear;
  -moz-transition: all 1.0s linear;
  -ms-transition: all 1.0s linear;
  -o-transition: all 1.0s linear;
  transition: all 1.0s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="elem" class="transition linear scritta"></div>
</div>

Answer №1

Indeed, addClass operates synchronously. By examining the source code:

addClass: function( value ) {
  var classes, elem, cur, curValue, clazz, j, finalValue,
      i = 0;

  if ( jQuery.isFunction( value ) ) {
    return this.each( function( j ) {
      jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
    } );
  }

  if ( typeof value === "string" && value ) {
    classes = value.match( rnothtmlwhite ) || [];

    while ( ( elem = this[ i++ ] ) ) {
      curValue = getClass( elem );
      cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

      if ( cur ) {
        j = 0;
        while ( ( clazz = classes[ j++ ] ) ) {
          if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
            cur += clazz + " ";
          }
        }

        // Only assign if different to avoid unneeded rendering.
        finalValue = stripAndCollapse( cur );
        if ( curValue !== finalValue ) {
          elem.setAttribute( "class", finalValue );
        }
      }
    }
  }

  return this;
}

The same outcome can be achieved using native APIs rather than jQuery.

var elem = document.getElementById('elem');

elem.classList.remove('transition');
elem.style.left = '200px';
elem.classList.add('transition');
elem.style.left = '0px';
#container {
  position: relative;
  width: 400px;
  height: 200px;
  background-color: red;
}
#elem {
  width: 50px;
  height: 50px;
  position: relative;
  left: 0;
  top: 0;
  background-color: blue;
}
.transition.linear.scritta {
 -webkit-transition: all 1.0s linear;
 -moz-transition: all 1.0s linear;
 -ms-transition: all 1.0s linear;
 -o-transition: all 1.0s linear;
 transition: all 1.0s linear;
}
<div id="container">
 <div id="elem" class="transition linear scritta"></div>
</div>

Browsers delay direct updates when modifying CSS styles to optimize performance, preventing unnecessary renderings and layouts that are costly when multiple style changes are involved.

To work around this limitation, consider employing asynchronous code:

requestAnimationFrame(function() {
  elem.style.left = '0px';
});

var elem = document.getElementById('elem');

elem.classList.remove('transition');
elem.style.left = '200px';
elem.classList.add('transition');
requestAnimationFrame(function() {
  elem.style.left = '0px';
});
#container {
  position: relative;
  width: 400px;
  height: 200px;
  background-color: red;
}
#elem {
  width: 50px;
  height: 50px;
  position: relative;
  left: 0;
  top: 0;
  background-color: blue;
}
.transition.linear.scritta {
  -webkit-transition: all 1.0s linear;
  -moz-transition: all 1.0s linear;
  -ms-transition: all 1.0s linear;
  -o-transition: all 1.0s linear;
  transition: all 1.0s linear;
}
<div id="container">
   <div id="elem" class="transition linear scritta"></div>
</div>

Alternatively, forcing an update using getComputedStyle appears to be effective as well.

getComputedStyle(elem).transitionDuration; // force update

var elem = document.getElementById('elem');

elem.classList.remove('transition');
elem.style.left = '200px';
elem.classList.add('transition');
getComputedStyle(elem).transitionDuration; // force update
elem.style.left = '0px';
#container {
  position: relative;
  width: 400px;
  height: 200px;
  background-color: red;
}
#elem {
  width: 50px;
  height: 50px;
  position: relative;
  left: 0;
  top: 0;
  background-color: blue;
}
.transition.linear.scritta {
 -webkit-transition: all 1.0s linear;
 -moz-transition: all 1.0s linear;
 -ms-transition: all 1.0s linear;
 -o-transition: all 1.0s linear;
 transition: all 1.0s linear;
}
<div id="container">
 <div id="elem" class="transition linear scritta"></div>
</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

Is there a way to modify the default color when the header is assigned the "sticky" class?

Currently, I am in the process of building my own website and have implemented an exciting hover effect that randomly selects a color from an array and applies it when hovering over certain elements. However, once the cursor moves away, the color reverts b ...

Problems with CSS animations on mobile devices in WordPress

On my website powered by Elementor Pro, I have implemented custom CSS to animate the Shape Divider with a "Brush Wave" style. Below is the code snippet: .elementor-shape-bottom .elementor-shape-top .elementor-shape body { overflow-x:hidden; } @keyframes ...

Issue with Jquery AJAX success function specifically in Firefox browser, while other functions in the script are functioning correctly

I have 4 scripts using ajax, but one of them isn't functioning properly in Firefox. Even the alert in success doesn't trigger anything. There are no error messages, just nothing happening. However, it works perfectly fine in IE and Chrome. Belo ...

Various Ways to Add Hyperlinks in HTML Using CSS Styles

Does anyone know how I can link multiple HTML files to one hyperlink, where only one file opens randomly when clicked? I am currently using . Your assistance would be greatly appreciated! I've tried searching online for a solution, but haven't ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Tips on avoiding the collapse of the right div when positioned under a left float in a full page layout

Trying out a full page layout for the first time, with a left div serving as a block style nav. #admin_nav { width: 230px; height: 100%; background-color: #f9f9f9; border-right: 1px solid #ddd; float: left; } The content is on the rig ...

Comparing Jscript's impact on CSS classes to the power of Json

On my HTML page, there is a div that looks like this: <div class="circle active" id="prg_inizio"> bla bla bla </div> After making an Ajax call, I receive a JSON result and need to update the class name from "circle active" to "circle done." ...

Error: CSS and JavaScript files cannot be found

Currently working with an Orchard Asp.net MVC 3 Project. Upon examining the source code in the browser, I notice all the JS and CSS files being referenced/imported. However, clicking on the URL for certain JS files located in the MediaLibrary or Modules f ...

utilizing jquery to transfer selections from one text box to another

I need help with a scenario where I have two text boxes aligned horizontally. The first textbox has a dropdown list from which multiple items can be selected. There is an "add" button positioned between the two text boxes. My goal is to click on the add ...

complex selection challenge

I'm curious about how to target a specific class within the parent element of an element. Can you help with that? ...

Include IE-specific stylesheet code in your Angular application (version 1.2)

I would like to implement conditional IE CSS for IE8 and IE9 in my Angular application. The approach I took was to add the specific CSS files directly in the index file as shown below: <!-- Application main stylesheet --> <link href="styles/them ...

Unveiling the Art of Styling a Reactjs Component with CSS

Recently delving into the world of Reactjs, I've created a component that I'm eager to enhance with CSS :) This component consists of a few buttons and boxes that are revealed when a button is clicked. class Days extends React.Component { con ...

Tips for injecting animation into a DIV

I am trying to make a <div> element on my webpage expand to the full width and height of the screen. While I have managed to achieve this, I also want to implement an animation that will be displayed when the <div> enlarges to fit the screen si ...

Experiencing blank areas when I try to minimize the screen while using Chrome

While using Chrome, my webpage looks perfect in normal mode. However, when I minimize the screen, white space appears at the bottom and some content gets hidden. The page is built using reactjs, html, and css. Interestingly, it works fine for IE in both no ...

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

AngularJS - Calculate multiple currencies

I need to calculate the product of a value and months. For the input value, I am utilizing a Jquery Plugin to apply a currency mask. Unfortunately, the calculations are not functioning properly with this plugin. My goal is to multiply the value, includin ...

"What is the best way to display a flash message upon successful completion of an AJAX request in Laravel

Is there a way to display a flash message after an ajax request redirects to a view? I'm having trouble getting the message to show up. Below is my code: Controller Code: \Session::flash('success', __('Password change successf ...

Scrolling with Jquery window.scrollTo results in the page becoming unresponsive

I'm currently revamping a website that features a header with 100% screen height, but I need it to shrink down to 0px when a user starts scrolling. The issue I'm facing is that once the header shrinks to 0px, the page content ends up slightly abo ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

Interactive JavaScript button that navigates me to a document without the need to click

I'm facing an issue with my small project. I've been learning javascript and managed to create a script that calculates the square of a number provided by the user. var checkIt = function(){ var theNumber = Number(prompt("Please enter a number ...