Animating text with jQuery: Simultaneous color transition guide

I'm trying to achieve a seamless transition of movement and color change in my web project. Currently, the text is animated first, and only afterward does the color change take place. How can I make the text change color while it's moving?
This is the HTML code:

<button type="button" class="btn btn-danger center-block" id="btn">start animation</button>
<div id="meterText" class="col-centered"></div> <!-- animated text -->

CSS:

#meterText{
    display:none;
    width: 50px;
    height: 10px;
    margin-left: 40px;
    position: absolute;
    top: 211px;
    font-size: 15px;
    color: red;
}


jQuery:

var counter=0;

$("#btn").on('click',function(event){
    counter++;
    console.log(event.target.id + " was clicked");
    switch(counter){
        case 1:{
            $("#meterText").text("first transition");
            $("#meterText").hide().fadeIn();
            break;
        }
        case 2:{

            $("#meterText").animate({'marginTop':"-=83px"});
            $("#meterText").text("second transition");
            $("#meterText").animate({color: "#FFD700"});
            break;
        }
        case 3:{
            $("#meterText").text("third transition");   
            $("#meterText").animate({'marginTop':"-=68px"});
            $("#meterText").animate({color: "#44c767"});
            break;
        }
    }
});

Link to the working example on jsFiddle

Answer №1

When using the animate function in jQuery, animations typically run one after the other. This means that if you have multiple animations, the second one will only start once the first one has finished. I was curious as to why the code was written on separate lines when it could easily be simplified into a single line.

$("#meterText").animate({'marginTop':"-=83px",color: "#FFD700"}).text("second transition"); 

Answer №2

Let's run the animations all at once:

Take a look at the DEMO

$("#meterText").animate({'marginTop':"-=83px",color: "#FFD700"});

Answer №3

For optimal results, I recommend utilizing CSS for automatic transitions. Simply add the following code snippet to your CSS selector:

-moz-transition-duration: 0.6s;
-o-transition-duration: 0.6s;
-webkit-transition-duration: 0.6s;
 transition-duration: 0.6s;

Then, in your jQuery script, replace .animate with .css for smoother functionality. You can set the duration directly from the CSS itself. Check out the example below:

var counter=0;

$("#kickme").on('click',function(event){
counter++;
console.log(event.target.id + " was clicked");
switch(counter){
case 1:{
$("#meterText").text("first transition");
$("#meterText").hide().fadeIn();
break;
}
case 2:{
$("#meterText").css({'marginTop':"-=83px","color": "#FFD700"});
$("#meterText").text("second transition");
break;
}
case 3:{
$("#meterText").text("third transition");
            $("#meterText").css({'marginTop':"-=68p","color": "#44c767"});
break;
}
}

});
#meterText{
display:none;
width: 50px;
height: 10px;
margin-left: 40px;
position: absolute;
top: 211px;
font-size: 15px;
color: red;
    -moz-transition-duration: 0.6s;
-o-transition-duration: 0.6s;
-webkit-transition-duration: 0.6s;
transition-duration: 0.6s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-danger center-block" id="kickme">kick me!</button>

<div id="meterText" class="col-centered"></div> <!-- meter's text -->

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

Traversing an array of objects to locate a specific key

I have an array of objects structured as follows: data = [ { "AccountType":"Client", "DeploymentList": { "-L3y8Kpl5rcvk-81q004": { "DeploymentKey":"-L3y8Kpl5rcvk-81q004", "DeploymentName":"Testing 3" ...

JavaScript expression not being processed

What could be the reason behind not receiving the value for dish.price, dish,description, etc.? Where am I making a mistake in this code snippet? <!DOCTYPE html> <html lang="en" ng-app> <head> <meta charset="utf-8"> < ...

Storing the output value of a JavaScript function in robot framework selenium2library results in a returned value of

My main goal is to automatically click on all the links present on a web page and then close any tabs that open up as a result. The structure of these links is like this: <ul> <li> <a href=#>random text</a> </li> ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

What is the process for obtaining the dimensions (height/width) of a particular instance within a dynamically rendered list?

[QUESTION REVISED FOR CLARITY] I am attempting to retrieve the dimensions, specifically the width and height, of a rendered <div/> within the Child.js component. While I found a helpful example on Stack Overflow, my scenario involves multiple dynami ...

Frequently encountering broken styles in Magento 1.9 due to missing CSS and JS files

Recently, I've been facing frequent style breaking issues on my Magento sites (1.9.2+). This results in the home page displaying only text with missing CSS, JS, and images. To fix this problem, I usually clear the cache by deleting the var/cache fold ...

Converting a PHP timestamp to a jQuery-compatible format

Can someone help me find the equivalent function in jQuery that will give me a time format similar to this: date( 'Y-m-d\TH:i:sP'); //the output is like this. 2013-10-30T18:10:28+01:00 I am looking for this specific format in jQuery to use ...

Troubleshooting Vue 3: Dealing with Synchronization Issues Between Keyboard Input and

I am currently working on a Vue 3 autocomplete component and I've come across a strange issue that I can't quite figure out. The component emits two events: "update:search" to update the search variable in the parent component, and "change" whic ...

Having trouble with Resizing Images in jQuery despite successful image rotation

I am facing an issue with rotating and resizing an image using an HTML5 form. The rotation angle can be adjusted in steps of 90 degrees, but the image should always remain 770px wide regardless of its orientation (landscape or portrait). Despite creating ...

The URLs seem to have a tendency to randomly incorporate the controller's name

I am facing an issue with my controller class named HomeController and the client-side JavaScript code: function upload(content) { var ajax = new XMLHttpRequest(); ajax.open("POST", 'UploadImage', false); ajax.setRequestHeader(' ...

Exploring the power of Angular JS and Ionic by parsing data from a JSON

I'm currently developing an App with the IONIC framework and Angular JS, utilizing the Tinder cards feature recently introduced by Ionic (http://ionicframework.com/blog/tinder-for-x/). My goal is to read from a JSON file and use it as storage for my a ...

Ways to showcase additional content

When I receive a JSON Object containing posts from a WordPress account, it only includes about 15 posts. What steps can I take to retrieve more than that amount? The structure of the JSON data is as follows: { ID: 4164, title: "24 Hour Non-Stop with Ma ...

Click on an element using jQuery to apply a specific class to all other similar

I am looking to dynamically add a class to a DIV after clicking on an A element with the same class. Here is an example: <ul> <li><a href="#1" class="test1">1</a></li> <li><a href="#2" class="test2">2</a>< ...

The peity function in Angular JS seems to be malfunctioning when used in conjunction with

When it comes to creating a basic pie chart, I like to use piety. It's simple to work with and functions well with JavaScript. Here is an example in HTML: <span class='pie' data-peity='{ "fill": ["#1ab394", "#d7d7d7", "#ffffff"]}&a ...

Converting HTML elements into a JSON object using jQuery

Is there a way to format an object like this from HTML using a button click? var Movie = [{id:"tt3783958", title:"La La Land", type:"Comedy, Drama, Music", year:"2016"}]; Can we then append the next object on the next button click with a format like this ...

What is the best way to place a dragged item on top of a dropped item?

I'm attempting to transfer data between two kendo grids using HTML5 drag and drop events. However, when I use ev.target.appendChild(document.getElementById(data));, I receive an error stating that data is not a node type. My goal is for the dropped da ...

The data received from the webservice is in proper JSON format, however, the jqGrid does not display the

Within my webservice, I have created a class called JqGridData to handle data population. This class was inspired by a previous thread authored by Oleg. The structure of JqGridData is as follows: public class JqGridData { /// <summary> / ...

Instructions on how to showcase a standard text within a designated text container

I am currently facing an issue with a textarea or textbox that is dynamically receiving URLs from a database. The textbox is displaying the full URL address, which is not visually appealing. I would like to replace this with some generic text such as "cl ...

LabeFor does not automatically create the display-lable class attribute

When setting up a new MVC project, the default Site.css file typically includes the following styles: /* Styles for editor and display helpers ----------------------------------------------------------*/ .display-label, .editor-label { font-weight: ...