Ensure that JavaScript finishes the animation before transitioning to the next step

Currently, I am developing a basic rotator that cycles through three pieces of advice on a website. My goal is to create a smooth fade in and out effect by adding and removing classes. While testing in the JavaScript debugger, everything runs smoothly as it steps through each call. However, when running the actual code, the transition appears choppy. I believe this happens because the script only focuses on adding the class without ensuring the transition within the class completes fully. I am seeking guidance on how to make sure the script finishes the transition entirely within the class. Below is the JavaScript function:

function rotateAdvice() {
  let nextAdvice;
  const currentAdviceCont = document.querySelector(".advice-show");
  const currentAdvice = currentAdviceCont.id.slice(-1);
  if (currentAdvice >= 2) {
    nextAdvice = document.getElementById("advice-0");
  } else {
    nextAdvice = "advice-"+(parseInt(currentAdvice) + 1);
    nextAdvice = document.getElementById(nextAdvice);
  }
  currentAdviceCont.classList.add("advice");
  currentAdviceCont.classList.remove("advice-show");
  currentAdviceCont.classList.add("no-display");
  nextAdvice.classList.remove("no-display");
  nextAdvice.classList.add("advice-show");
}
// The function is called using:
setInterval(rotateAdvice, 4000);

Below are the CSS classes used for the transition effects:

.advice {
    opacity: 0;
    transition: 1s opacity;
}
.advice-show {
    opacity: 1;
    transition: 1s opacity;
}
.no-display {
    display: none;
    visibility: hidden;
}

Answer №1

Utilize the transitionend event to achieve a more precise toggle effect.

Below is a snippet for reference:

var box1 = document.querySelector(".box.nr1");
var box2 = document.querySelector(".box.nr2");

box1.addEventListener("transitionend", trans_ended, false);
box2.addEventListener("transitionend", trans_ended, false);
setTimeout(function() { box1.classList.add('trans') }, 10);

function trans_ended (e) {
  if (e.type == 'transitionend') {
    if (e.target == box1) {
      box1.classList.remove('trans');
      setTimeout(function() { box2.classList.add('trans') }, 10);
    } else if (e.target == box2) {
      box2.classList.remove('trans');
      setTimeout(function() { box1.classList.add('trans') }, 10);
    }
  }
}
.box {
  position: absolute;
  left: 1em;
  top: 1em;
  width: 5em;
  height: 5em;
  background-color: blue;
  opacity: 0;
  transition: opacity 2s;
}
.box.nr2 {
  background-color: red;
}
.box.trans {
  opacity: 1;
}
<div class="box nr1"></div>
<div class="box nr2"></div>


Another method is using animation, which allows for more dynamic effects.

Here's another one of my responses related to this topic:

  • Altering an HTML element's style in JavaScript when its CSS transition is temporarily disabled may not work reliably

Answer №2

My solution involved utilizing a basic event listener for the transitionend event. Here is how I implemented it:

  adviceContainer.classList.add("advice");
  adviceContainer.classList.remove("show-advice");

  adviceContainer.addEventListener("transitionend", () => {
    adviceContainer.classList.add("hidden");
    nextAdviceElement.classList.remove("hidden");
    nextAdviceElement.classList.remove("advice");
    nextAdviceElement.classList.add("show-advice");});

}

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

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

Start the ng-app once the document has finished loading

I'm currently working on a project involving AngularJS. One of the specified requirements is to retrieve the HTML content that is "ng enabled" from the server upon a click event, and then inject it into a <div ng-app> using JavaScript. The iss ...

Ways to display the result in a new tab

I am using colorbox with a form that will be submitted to another website. I would like for the response from that web page to load in a new tab with a new URL. ...

Utilizing Squelize's junction table for forming new connections: a comprehensive guide

I am currently working with three basic tables: A, B, and C. The relationship between A and B is many-to-many, so I am using a junction table called A_B. Table C has a one-to-many relationship with the junction table A_B. In sequelize, this is how they are ...

Create dynamic and interactive content by embedding text within SVG shapes using the powerful D

How can I write text into an SVG shape created with d3.js and limit it to stay inside the shape similar to this example http://bl.ocks.org/mbostock/4063582? I attempted to use a clipPath following the example provided. However, when inspecting with firebu ...

Using Vue 3, Bootstrap, and Pinia to create an innovative Global Modal experience

After creating a ModalComponent.vue file that I intend to use across different sections, I encountered an issue with closing the modal after calling my Pinia stores. The modal includes slots for the title, body, and footer, along with a standard close butt ...

Promise.all() ensures that all promises in the array are resolved with the same value

Currently, I'm in the process of developing a module that contains a function designed to return a promise using Promise.all() for the purpose of sending emails to multiple users. By simplifying the code, I have managed to isolate and reproduce the is ...

Enhancing the session helper in Silex with additional values

Hey there, I'm currently working on a basic shopping cart using an MVC framework called Silex. However, I've run into a JavaScript/AJAX issue that I could use some help with. My problem arises when trying to add a product to the basket. The issue ...

Switch between different data objects using ajax

Is there a way to toggle between two AJAX data objects by clicking on a link? The current method I am using doesn't seem to work. Any suggestions on how this can be achieved? Thank you! jQuery.ajax({ url: "/somefile.php", dataType: 'JSON&apo ...

The specified property 'length' is not found on type OkPacket within the mysql2 module

In my code example below, I am simply showcasing a specific scenario: this.getCode = (code: string): Promise<codeObject | false> => { return new Promise((resolve, reject) => { pool.query('SELECT * FROM ?? WHERE code = ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

Using jQuery, locate identical text and assign a class to the corresponding container

How can I check if any of the h2 elements match the text in h1, ignoring case sensitivity? If a match is found, I want to add a class to the container Product-div. <div id="PageHeader"> <h1>Same text</h1> </div> <div class= ...

Filtering data with AngularJS upon user clicks

Encountering a perplexing issue at the moment. I have created buttons using ng-repeat and my intention is for them to filter my list when clicked on. However, I am facing an issue where the list fails to filter upon clicking. Here are the buttons: <div ...

What are some effective ways to stretch specific muscles?

I am facing an issue with my select element. The default value is "please choose," but there are options like "Accommodation & Hotels" that are longer and not clearly visible on IE browsers, though they work fine in Firefox. How can I resolve this issue? S ...

Tips for embedding a colorbar image into a select dropdown menu

Currently working on an HTML page that requires a dropdown menu to select between two different colorbars for a graph. The dropdown options should display the colormaps visually, so I am looking to include either: An image of the colorbar A gradient back ...

Ways to repair the mouse hover transform scale effect (animation included)

I am currently facing an issue with my GridView that contains images. When I hover over the top of the image, it displays correctly, but when I move to the bottom, it does not show up. After some investigation, I suspect that there may be an overlay being ...

Exploring the use of jQuery or other JavaScript libraries for creating dynamic web applications

After completing a mid-level web application recently, I utilized Telerik controls along with native JavaScript functions in collaboration with other developers on the project. We encountered numerous cross-browser issues using this approach, although we ...

Running code sequentially in a Node.js controller

Recently delved into the world of Node.js, and I'm currently tackling the challenge of running this code synchronously in my controller. Quest.js async function create(req, res, next) { const formValue = req.body['form']; ...

Exploring the World of AngularJS Modules

I'm a beginner in AngularJS and currently learning the ropes. I came across this syntax: var app = angular.module('myApp', ['ngRoute']); My question is, what does it mean when square brackets are used [ ]? What roles or function ...