The magic of coding is in the combination of Javascript

My goal is to create a CSS animation using jQuery where I add a class with a transition of 0s to change the color, and then promptly remove that class so it gradually returns to its original color (with the original transition of 2s).

The code below illustrates my issue. Why does the blue1() function not work as expected? It seems like the JavaScript executes too quickly for the new class to be added to the element, but I'm unsure about the inner workings of this process. However, if I add the class and then wait before removing it, as shown in blue2(), it works fine. Is there a more effective way to achieve this effect? What would be the optimal workaround?

Thank you.

Snippet:

function blue1(){
$("#element").toggleClass("blue");
$("#element").toggleClass("blue");
}

function blue2(){
$("#element").toggleClass("blue");
setTimeout(function(){
$("#element").toggleClass("blue");
}, 1000);
}
#element{
width:100px;
height:100px;
background:red;
transition:2s;
}

#element.blue{
background:blue;
transition:0s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>

<div id="element"></div>
<button id="button" onclick="blue1();">Run without delay</button>
<button id="button2" onclick="blue2();">Run with delay</button>
  
</body>
</html>

Answer №1

function toggleColor(){
  var transition = $("#element").is(".delayRed");
  if(transition){
    $("#element").removeClass("delayRed");
  }else {
    $("#element").toggleClass("red");
  }

}

function delayColorChange(){
  var alreadyRed = $("#element").is(".delayRed");
  if(!alreadyRed){
    setTimeout(function(){
$("#element").toggleClass("delayRed");
}, 1000);
  }
}
#element{
width:100px;
height:100px;
    background:blue;
}
#element.red{
width:100px;
height:100px;
    background:red;
}

#element.delayRed{
width:100px;
height:100px;
background:red;
    transition:2s;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="element"></div>
<button id="button" onclick="toggleColor();">Run without delay</button>
<button id="button2" onclick="delayColorChange();">Run with delay</button>
  
</body>
</html>

I made some changes to the code according to Bruno's specifications and included additional CSS for toggling between two colors. Note that transitioning to red is only allowed if the square doesn't already have the class red.

Documentation:

removeClass()

is()

Answer №2

The issue with your concept not functioning correctly stems from jQuery's indifference towards any transitions on the class responsible for fading the blue background.

When you execute toggleClass(), it examines the element and either adds or removes the class. Initially, it adds the class; however, upon subsequent calls, it detects the class's presence and promptly eliminates it. This removal of the class also nullifies any ongoing transition effects.

A more effective approach, if your sole objective is to modify the background color, involves employing jQuery transitions along with a precise selector targeting your button instead of embedding the function within the HTML. Consider the following code snippet:

$('#button1').onclick(function() {

  $(this).animate({
    background: 'blue'
  }, 2000, function() {

    $(this).animate({
      background: 'red'
    }, 2000);

  });

});

The above script establishes an event listener for your button click action and utilizes the .animate() method to animate the background property of the element to blue. A callback function is set to revert the background to red after 2 seconds. Adjust the timing parameters for different durations, and I recommend consulting the documentation for the animate() method provided in the link below.

http://api.jquery.com/animate/

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

How about "Incorporate Google Auth into your Vue.js project with modular

I'm on the search for a project that showcases using Vue.js and the Google client library to authenticate with JavaScript, but without the need for transpilers, bundlers, or Node/npm. Does anyone know of such an example out there? I simply want to cre ...

Guide to emitting a value using the composition API

I'm currently working with a datepicker component that is part of a form in my Vue3 app using the composition API. My challenge is how to pass a value from the datepicker component back up to the form component. Unfortunately, I've encountered ...

Unable to iterate through nested arrays in Contentful mapping

I am facing an issue while trying to map further into the array after successfully retrieving data from Contentful. The error message field.fields.map is not a function keeps popping up and I can't figure out what I'm doing wrong. export defau ...

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

setting a variable with data retrieved from an AJAX call using jQuery

Here's a snippet of jquery code that I'm working with: var example = "example"; $.ajax({ url: root + "/servletPath", type: "GET", success: function (response) { alert(response); // displays the correct value example ...

HTML code featuring multiple dropdown menus, each equipped with its own toggleable textarea

I have multiple HTML drop downs, each triggering a textarea based on the selection. Currently, I'm using show and hide JavaScript functions for each question individually. Is there a way to streamline this so that I don't have to write separate c ...

How can I keep the CSS3 animation playing even after the hover state ends?

When hovering over the small menu logo on my site, there's a subtle wiggle effect that I really like. However, I would prefer if the animation played all the way through before repeating. Here's the code I'm currently using: Here is my code ...

What is the best way to select an element that is currently visible but hidden underneath another element?

I have developed a circular graphic using primarily HTML and CSS, with some JavaScript and JQuery functionalities incorporated for text curving and planned interactions in the future. However, I've encountered an issue where clicking on the upper rig ...

Refresh the information on the page by loading data from the log file using AJAX

I am currently running a shell script in the background and directing the output to a log file using PHP. I'd like to showcase the content of this log file on the webpage, which I've managed to achieve with the following code snippet. <?php ...

Change the color of the background in the Material UI Snackbar

Whenever I try to change the background color of the Snackbar by setting a className, it doesn't get applied properly. Instead, for a brief moment when the page renders, the desired background color appears and then quickly gets replaced. I've g ...

Enhancing AngularJS routing with dynamic partial parameters

I have experience working with routes in different frameworks like Rails and Laravel, but I am now facing a challenge while working on an AngularJS site. In Laravel, we could dynamically create routes using foreach loops to handle different city routes. Ea ...

Using withRouter() to redirect will display all components

I'm brand new to Reactjs and am currently diving into routing. In my journey, I stumbled upon the use of withRouter() for programmatic redirection. I had assumed the flow would follow: constructor->Willmount->render, but it seems the current or ...

"Discover the steps to efficiently utilize the lookup feature with array objects in MongoDB

I am a beginner with MongoDB and I am trying to create a schema for my collection as shown below please note that all ObjectId values are placeholders and not real stockIn documents { serial:"stk0001", date:'2021-06-11', productInTra ...

When inserting the HTML of a webpage into an iframe, the displayed content may vary slightly from the original page

I am facing an issue with my webpage where I extract the html, transmit it via websockets using socket.io to another page containing an empty iframe, and then inject the html dynamically into the iframe. My code for injecting the html looks like this: fr ...

Does any jQuery grid compare to the ExtJs GridPanel when it comes to both aesthetics and performance?

After reviewing the jQuery grid suggestions mentioned on this link, I found that they lack the sleekness of the ExtJs GridPanel. Has anyone customized any of these options to resemble the ExtJs grid more closely? Or are there alternative recommendations n ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...

Utilizing JavaScript to bring JSON image data to the forefront on the front-end

In my quest to utilize JavaScript and read values from a JSON file, I aim to showcase the image keys on the front-end. To provide clarity, here's an excerpt from the JSON dataset: { "products": {"asin": "B000FJZQQY", "related": {"also_bought": ...

The insider's guide to understanding the inner workings of the :nth-child() property

I am finding the :nth-child() property to be a bit confusing. Sometimes it takes arguments like :nth-child(2),:nth-child(2n),:nth-child(2n + 1). I'm not sure what these mean exactly - are they referring to even or odd divs, or is there another propert ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

The styling in CSS does not accurately reflect its relationship to the parent

My code includes a div with the ID of "outer" nested inside a parent div with the ID of "Container". I'm attempting to adjust the properties of the outer div relative to its parent, meaning its width, height, and other attributes should be based on th ...