Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter.

For example, when the counter reaches 50%, the green background should animate to cover 50% of the div height, all in sync and at the same speed, starting and stopping simultaneously.

I have provided my code on JSFiddle, but I'm aware that it's not running smoothly and the code looks a bit messy. http://jsfiddle.net/QGNKt/3/

Can someone help me clean up this code? Am I heading in the right direction? Assistance in improving the JSFiddle code would be greatly appreciated. I believe the current code might work eventually, but it seems too disjointed - although maybe what I have now will suffice - who knows!

<head>
    <style type='text/css'>
        #container {
            position: relative;
            overflow: hidden;
            height: 60px;
            width: 100px;
        }

        #green {
            height: 600px;
            width: 100px;
            background: #090;
            position: absolute;
            top: 60px;
            left: 0;
        }
    </style>

    <script type='text/javascript'>//<![CDATA[ 
        $(window).load(function () {
            function createCounter(elementId, start, end, totalTime, callback) {
                var jTarget = jQuery("#" + elementId);
                var interval = totalTime / (end - start);
                var intervalId;
                var current = start;
                var f = function () {
                    jTarget.text(current);
                    if (current == end) {
                        clearInterval(intervalId);
                        if (callback) {
                            callback();
                        }
                    }
                    ++current;
                }
                intervalId = setInterval(f, interval);
                f();
            }
            jQuery(document).ready(function () {
                createCounter("counterTarget", 0, 50, 2000, function () {
                    //alert("finished")
                })
            })
            //]]>

            $(document).ready(function () {

                $('#green').animate({
                    top: 40
                }, 2300, function () {
                    //$('#button').val('down');
                });
            });
        });//]]>  

    </script>
</head>
<body>
    <h1 style="font-size: 135px" id="counterTarget"></h1>
    <h1 class="f-l">%</h1>

    <div id="container" style="border: Red solid 1px;">
        <div id="green"></div>
    </div>
</body>

Answer №1

I have optimized your code and made some improvements. Have you considered using existing solutions for progress bars and similar components? Take a look at Twitter Bootstrap.

Check out this Fiddle: http://jsfiddle.net/BenedictLewis/QGNKt/6/

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

Exploring the Benefits of Using JSON in AJAX Requests

Can you help me determine the best way to extract data from a php page using ajax in the form of a json array? Here is an example code snippet: $.ajax({ type: "get", url: "assets/update_cart_user_fstore.php", data: up, cache: false, su ...

Scroll to the top of a new page with Material UI's table component

Feeling a little stuck here. I've tested various settings with scrollTop, but haven't had much luck. To clarify, I'm working with Material UI and their pagination features in conjunction with a table (you can find the documentation here). W ...

Leveraging the power of `.vue` files in modern web browsers that have native support for

Chrome 60 and the most recent version of Firefox, when used with certain flags enabled, have implemented support for import/export directives. I am interested in utilizing .vue files without relying on NodeJS, but I haven't been able to figure out how ...

Inserting items into the document after updating the list with fresh data

I populate an array of objects when a button is clicked. The array only has 10 objects initially, but users can add more after it's loaded into the DOM. Here's how I handle this: $scope.Information = []; $.each(data, function (i, v) { if ...

What is the best way to trigger a jQuery function only after the previous execution has completed?

As I set out to create a full-width image carousel/gallery for my portfolio independently, an initial idea that crossed my mind was simply shifting the entire image block gallery_wrapper to either the left or right by applying a positive or negative margin ...

Steps for inserting new text in front of an element's existing text

Is there a way to insert text before the original content of an element? I know how to add text after using createTextNode, as shown in this example: $("#button").click(function() { $( ".text" ).append( document.createTextNode( " Hello" ) ); }); < ...

Utilize the event bus by calling `this.$root.$emit` command

I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit and $on methods as shown below: EventBus.$on and EventBus.$emit('call ...

What is the reason that the select option change event does not allow the use of "this" and event.target to access the selected value

Why is it difficult to obtain the selected value in a select option change event using this or event.target, and instead needing to use cumbersome code like $( "select option:selected" )? This issue arose when I needed to access certain data-* attributes ...

Extending State Interface in ReactJs and Typescript: A Step-by-Step Guide

I have the following: interface EditViewState<T> { entity?: T; } abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> { constructor(props: P, ctx: any) { super(props, ctx); this. ...

Automatically switch Twitter Bootstrap tabs without any manual effort

Is there a way to set up the Twitter Bootstrap tabs to cycle through on their own, similar to a carousel? I want each tab to automatically switch to the next one every 10 seconds. Check out this example for reference: If you click on the news stories, yo ...

Mix up table data cells using Javascript/jQuery

Can anyone provide me with some helpful tips? I'm really struggling with this. My Objective I aim to create a table with two columns ("name" and "rating"), consisting of 5 rows. 2 of these rows should have a random "rating" between 6-10 2 other ro ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

I encountered a RangeError with code [ERR_HTTP_INVALID_STATUS_CODE] due to an invalid status code being undefined

I have encountered a specific error while running my note-taking app. The error seems to be related to the following piece of code - app.use((err,req,res,next)=>{ res.status(err.status).json({ error : { message : err.message ...

Utilizing React Selector: Propagating the onChange Event Up Two Components

Struggling to pass an onChange event from React selector through two components back up to the parent App. The issue is that e.target.value is coming back as undefined, indicating that the event might not be returning properly. Can someone pinpoint what&ap ...

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

Having trouble clicking the button due to the overlay blocking it?

This code contains the HTML portion <li id="nav1" class="navs"><a unselectable="on" draggable="false" class="Navigation" href="http://youtube.com">YouTube</a></li> Below is the CSS code .navs:after { content: ""; position: ab ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Learn how to display separate paragraphs upon clicking a specific item

New to coding and eager to learn, I have recently started exploring HTML, CSS, and basic JavaScript. In my journey to enhance my skills, I am working on building a website for practice. One particular page of the site showcases various articles, each acc ...