What is the correct timing for implementing a JavaScript delay to activate CSS styling?

Let's say I have some CSS like

#joe { transition: opacity 500ms; opacity: 0; }

Next, I include JavaScript that triggers the addition of a div and then animates the opacity to = 1 when you click the page.

document.body.onclick = function () {
  var joe = document.createElement('div')
  joe.innerHTML = 'yo!'
  joe.id = 'joe'
  document.body.appendChild(joe)
  joe.style.opacity = 1
}

However, the animation doesn't occur. (Possibly due to the CSS transition treating it as an 'initial page load')

If a timeout is added

document.body.onclick = function () {
  var joe = document.createElement('div')
  joe.innerHTML = 'yo!'
  joe.id = 'joe'
  document.body.appendChild(joe)
  setTimeout(function () {
    joe.style.opacity = 1
  }, 100)
}

Then the animation functions.

Yet, in some cases, even a 100ms delay impacts the page's responsiveness. Unfortunately, setting the timeout to 1ms doesn't resolve the issue.

So, what would be the ideal timeout setting? I seek an animation that consistently operates effectively on major browsers without unnecessarily prolonging the timeout.

I prefer CSS transitions over jQuery animation due to efficiency and synchronization advantages. I'm open to suggestions for alternative JavaScript approaches, but please provide an answer to the question.

If there is an initial animation option in CSS, I would appreciate knowing about it...

However, my primary concern is determining the proper timeout setting, especially when animating properties like left or width where CSS may not be flexible for dynamic value calculation using JavaScript.

Answer №1

One way to achieve this without using setTimeout is by utilizing the

window.<a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle" rel="nofollow">getComputedStyle()</a>
method.

The basic concept is as follows:

joe.style.opacity = 0; //not needed in this scenario, as set by CSS class   
window.getComputedStyle(joe).getPropertyValue("width");
joe.style.opacity = 1;   

You can view an example in action on jsfiddle: http://jsfiddle.net/4Vy9n/2/

Answer №2

Extremely straightforward, behold a CSS solution in its purest form:

See It In Action http://jsfiddle.net/X7Zg5/7/

CSS:

.joe {
    font-size: 100px;
    -webkit-animation-duration: 500ms;
    -webkit-animation-name: fadeIn;
    -moz-animation-duration: 500ms;
    -moz-animation-name: fadeIn;
    -o-animation-duration: 500ms;
    -o-animation-name: fadeIn;
    animation-duration: 500ms;
    animation-name: fadeIn;
}
@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
@-webkit-keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
@-moz-keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
@-o-keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

JS:

document.documentElement.onclick = function () {
    var joe = document.createElement('div');
    joe.innerHTML = 'yo!';
    joe.className = 'joe';
    document.body.appendChild(joe);
}

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

Arrange the array in chronological order based on the month and year

I'm looking for assistance with sorting an array by month and year to display on a chart in the correct order. Array1: ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'....]; Desired Output: ...

`Anomaly detected in image grid display`

The images are not resizing according to the container. Despite setting both height and width to 100%, the image is not taking the width of the outer column container. https://i.sstatic.net/10eMg.jpg This is what I expected This is the result I am current ...

What is the best way to limit data loading when tabs are clicked in an AngularJS application?

My application has 2 tabs and all data is fetched from an API response. Initially, all data is loaded at once. The two tabs are: Tab 1 Tab 2 By default, Tab 1 is always active. I only want to load data for Tab 1 initially and not for Tab 2. When I c ...

Error message: Unable to access $controller with AngularJS and Karma

As someone who is just starting with testing, I figured it was a good idea to begin testing this project. However, when I execute grunt karma:watch, I encounter an error related to the configuration files. My config file includes: module.exports = functi ...

Sending a JavaScript variable to PHP and retrieving the PHP result back into a JavaScript variable

I am looking to transfer a JavaScript variable to a PHP file using AJAX, and then retrieve the PHP file's output back into a JavaScript variable. For sending the JavaScript variable to the PHP file, I found a method that suggests using ajax to assign ...

The function ensure_csrf_token is failing to set the CSRF cookie in the cookies section

I am facing an issue with setting up a CSRF token in my application. Firstly, I have a simple generic view in Python: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, ...

What is the best way to access the child component in React?

const navArr = [ { path: "/introduction", title: "회사소개", subTitle: [{ title: "summary" }, { title: "vision" }], }, ] {navArr.map((obj) => { return ( <NavItem> ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

What is the best way to replace a CSS Background that is already marked as important?

Attempting to change the background of a website using Stylish, but encountering issues. The existing background css on the website includes an !important rule which is preventing Stylish from taking effect. Here is my code: body { background-image: n ...

the status of the XMLHttpRequest Object within the realm of jQuery AJAX

When using traditional JavaScript AJAX, we monitor the readystate property to determine the status: 0 - The request is not initialized 1- The request has been set up 2 - The request has been sent 3 - The request is in process 4 - The request is compl ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

How can I choose the first n children up to a certain class using CSS?

Take a look at this HTML : <div class="container"> <a id="1"></a> <a id="2"></a> <a id="3"></a> <a id="4"></a> <a id="5" class="specific"></a> <a id="6"></a ...

Is there a way to shade the entire webpage background in HTML?

Instead of affecting other DOM classes, I tried using another div but it doesn't darken the whole page. This means I have to manually modify each DOM class. Is there a way to overlay the entire document with a semi-transparent gray plane? ...

What is the best way to align this content in a specific area?

How can I center the content in each section of my webpage? Here is an image for reference: https://i.stack.imgur.com/PHEXb.png I want Section 1 and Section 2 to be 100vh with the content centered on the page. .content { height: 100vh; } <!do ...

What is the process for creating a line using points in three.js?

Can anyone provide a solution for creating a straight line using new THREE.Points()? I attempted to place particles and set their positions with an array and for loop, but the spacing was inconsistent. ...

The function maybeStripe.apply is not defined

Greetings, Encountering a Stripe error in Gatsby upon page load Error: Uncaught (in promise) TypeError: maybeStripe.apply is not a function import React, { useEffect, useState } from 'react'; import { loadStripe } from '@stripe/str ...

Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage. Here is how the process unfolds: When a user clicks on ...

Utilizing Angular 6's Mat-Table in a dynamic way

I am currently working on an Angular application that involves displaying data fetched from an API. The challenge I'm facing is that I do not have prior knowledge of the data I will be retrieving. Additionally, I need to create a model that can be use ...

Attempting to showcase a list of 4 concatenated items in a dropdown menu sourced from the database

I am attempting to concatenate and display 4 items in a dropdown list using AJAX. For example, the value in the dropdown list should appear as (127, CoilWt, 1, KGS) from the database. In the database, I am selecting select CODE_VALUE, CODE_DESC, CODE_SUB ...

Establishing express routing results in API call returning 404 error indicating resource not found

I need some clarification on how to configure my Express routing using app.use and router. My understanding is that I can create a router and then attach it to a route using app.use() to handle all routing related to that route. Can someone assist me in ...