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

Does the "too much recursion error" result from the if clause?

Before I send my form data to a PHP script, I am performing a jQuery check: $(document).ready(function(){ $("#submit").submit(function(e){ var vari1 = $("#inputhidden1").val(); var vari2 = $("#inputhidden2").val(); if(vari1 == 1) { ...

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...

Sending variable data through AJAX: A comprehensive guide

After sending the variable data through ajax to the loading_add.php page, I encountered an error message: Uncaught ReferenceError: profit is not defined. Below is what I have attempted so far: var profit = ( Number($("#pro_price").val() - retail_pri ...

Discover the step-by-step process of retrieving an image through jQuery AJAX in Laravel 8

I'm facing an issue while trying to download images using jQuery/AJAX in Laravel 8. Although I am able to retrieve the image in the response, it isn't downloading as expected. Could someone please assist me in resolving this problem? Controller ...

IE does not support hover effects

Having trouble with a hover effect that works in Chrome but not in MSIE. Are there any alternatives or fixes to make it work in MSIE? The hover/rollover effects I've tried all seem to have this issue in IE. normalize.css demo.css set2.css font- ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...

Don't forget to preserve the hover state of divs even after refreshing

I recently added a navigation bar that expands in width upon hovering over it. For an illustration, check out this example: http://jsfiddle.net/Gsj27/822/ However, I encountered an issue when clicking on a button within the hover effect area. After load ...

Expanded MUI collapsible table squeezed into a single cell

I'm experimenting with using the MUI table along with Collapse to expand and collapse rows. However, I've noticed that when utilizing collapse, the expanded rows get squished into one cell. How can I adjust the alignment of the cells within the p ...

Latest FF 35 showing alert for blank field in HTML5 email input box

My form includes an email input field with a default value. When the user focuses on the field, it clears out if the value matches the default one. Upon blurring the element, the default value is restored if the field remains empty. In Firefox 35, clickin ...

Setting the outcome of an Ajax call as a global variable in JavaScript

I have a method that uses AJAX to request data and returns a JSON string containing Tokens records. I am trying to store this result in a global variable named 'tokens' so I can access it in other functions. After assigning the result to the &ap ...

Here is a guide on how to ensure that the div elements automatically fill the available space

Looking at this html page: Check out the jsFidlle Demo here I am aiming to have the boxes fill up the space effortlessly, each with equal width but varying heights. This is similar to the layout in Google Keep notes ...

The process of organizing and arranging the content that appears on a webpage is in

Seeking a solution to achieve a similar effect like this example. Wanting the sections to transition nicely when clicked on. Should I use a Jquery plugin or implement it with CSS? ...

Guide to sending and receiving JSON data using XAMPP PHP

Currently, my XAMPP 7.1.10-0 server is up and running with the following index.php file: <?php if(isset($_POST["username"])) { echo $_POST; header("Location:getbooks.php"); exit; } else { echo file_get_conten ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

What is the process for including or excluding a class from a horizontal scrollbar?

I've been trying to implement a back to top button on a horizontally scrolling page. However, I'm encountering difficulties in adding or removing the necessary class to show or hide the button. Here's the JavaScript code I'm using: $( ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Stencil - React Integration Does Not Support Global CSS Styling

As per the guidance provided in the Stencil docshere, I have established some global CSS variables within src/global/variables.css. This file is currently the sole CSS resource in this particular directory. Upon attempting to incorporate my components int ...

When using Jest, the mongoose findOneAndUpdate function may return null values for both error and document

I've been struggling with Mongoose's findOneAndUpdate method as it doesn't seem to provide any useful information. I have tried accessing the Query returned from calling it (stored in updatedUser), but all it returns is null. Adding a callba ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

Splitting a CSS hierarchical list into horizontally aligned levels of hierarchy

I am trying to horizontally lay out an ordered list with multiple top level nodes while preserving the vertical layout of child nodes. For example, consider a basic list structure like this: <ol> <li>Top 1 <li>Sub 1</li ...