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

Continue to alter elements by stacking them on top of each other

Currently, I am in the process of familiarizing myself with CSS3 3D transforms. However, I am encountering difficulties in keeping elements that are undergoing transformation on top of other elements. If you'd like to take a look at what I have accom ...

Internal server error encountered while making an AJAX call using AngularJS routing

I'm currently diving into AngularJS with a basic application focused on customers and their orders. The issue I'm encountering involves a table that showcases the list of customers along with a link to access their respective orders. However, upo ...

Tips for incorporating properties from JSON-retrieved objects into a template

I'd like to extract and display only the state_name value from the HTML template. Is there a way to achieve this using jQuery in the template? $.ajax({ type: 'GET', url: "http://localhost:8000/country_state/", data: { "country": s ...

Ionic Troubleshoot: Issue with Reading Property

Encountering an error: A TypeError occurs: Cannot Read Property of "username" of Undefined The HTML code responsible for the error is as follows: <ion-content padding style="text-align: center; margin-top: 35px"> <form (ngSubmit)="logFor ...

Are you looking for a way to prevent the default behavior of an event in angular-ui-router 1.0.x? Check out

Recently, I made a change in my code where I replaced $stateChangeStart with $transitions.onStart $rootScope.$on('$stateChangeStart', function(e, ...){ e.preventDefault(); // other code goes here... }); Now, the updated code looks lik ...

Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA thro ...

`json: Alert not displaying response data`

Currently, I am utilizing the following Ajax code to retrieve data from the server. $.get("http://***/umbraco/Api/SomeApi/SignIn",{apiVersion : 1,email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee0efe3ebcee9e3efe7e2a0ed ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

Gain access to the iterable within the adjacent tag

I am looking to access an iterable from a sibling tag, but unfortunately it is within a table which complicates things. Simply wrapping the content in a div and moving the iteration outside is not possible due to the structure of table rows. Here is an exa ...

Maintaining active navigation state in JQuery/JavaScript after clicking a link: tips and tricks

While many resources discuss adding the active class to a nav link using jquery, there is less information on maintaining the active state after the nav link has been clicked. After experimenting with code from various sources, I have attempted to set ses ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

"An issue with AngularJS ngTable causing a delay in the rendering of Ajax

Struggling with ngTable Setup Having trouble mastering the use of ngTable by going through the ngTable ajax demo. I attempted to follow along with the example as closely as possible, but I'm encountering a deviation in defining an ngResource inline w ...

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

Rails 6: Issue with Ajax not recognizing the render method in js.erb files

I am currently facing a challenge in displaying the results of a SHOW action through AJAX. Within the show.js.erb file, the rendering works as expected with this code: $('#someid').html("<p>regular html</p>") This successfully rende ...

Loading background images in CSS before Nivo slider starts causing a problem

I've been struggling with preloading the background image of my wrapper before the nivo-slider slideshow loads. Despite it being just a fraction of a second delay, my client is quite particular about it -_- After attempting various jQuery and CSS tec ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

What is the best method for enabling communication between two users when the identification numbers created by socketIO are automatically generated?

Hey there, hope you're doing well. I've been pondering a question that has left me stumped. I recently came across a course that explained how to send a message to a specific user using socketIO.js by utilizing the `to()` method and passing the ...

AngularJS: Understanding the difference between ng-show and using display:none

I recently encountered a scenario where I needed to hide an HTML element by default using CSS. Here's how I did it: HTML: <div class="box"> </div> CSS: .box { display: none; } However, I wanted to be able to show and hide the elem ...

Contrast in executing an Arrow Function versus a regular Function when passing them as Props in REACTJS

Here is the component code: <SelectCampanha titulo="Preenchimento obrigatório" listaOpcoes={ category ? riskModel.filter((item) => item.CategoryType.includes(categoria) ...