Moving Image Progress Indicator

I am currently developing a progress bar animation that is designed to animate from 0 to a specified percentage when the progress bar becomes visible within the browser's viewport. The animation must always trigger when the element is scrolled into view, and scrolling it out of view should reset the animation.

Below is the code snippet that I have been working on:

var $animation_elements = $('.progressAnimation');
var $window = $(window);

function check_if_in_view() {
  var window_height = $window.height();
  var window_top_position = $window.scrollTop();
  var window_bottom_position = (window_top_position + window_height);
 
  $.each($animation_elements, function() {
    var $element = $(this);
    var element_height = $element.outerHeight();
    var element_top_position = $element.offset().top;
    var element_bottom_position = (element_top_position + element_height);
 
    //check to see if this current container is within viewport
    if ((element_bottom_position >= window_top_position) &&
        (element_top_position <= window_bottom_position)) {
        $element.animate({
            "width": (600 * $($element).data("percent")) / 100
        }, 3000);
    } else {
        $element.animate({
            "width": "0"
        }, 1000)
    }
  });
}

$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
 body{
            height:4000px;
            margin-top:800px;
        }
        .myContainer{
            width:1000px;
            margin:50px auto;
        }
        .myContainer .progressBackground{
            width:600px;
            height:40px;
            margin:0 auto 40px;
            background-color:#eaeaea;
        }
        .myContainer .progressAnimation{
            width:0;
            height:100%;
            background-color:#00f36d;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="myContainer">
        <div class="progressBackground">
            <div class="progressAnimation" data-percent="80">

            </div>
        </div>
        <div class="progressBackground">
            <div class="progressAnimation" data-percent="60">

            </div>
        </div>
    </div>

Please remember to run the code snippet in fullscreen mode for optimal viewing experience.

Answer â„–1

It is not advisable to animate using Javascript within a scroll/resize event without throttling the event. A simpler approach would be more efficient.

Instead of animating with Javascript, you can consider using CSS for animation and changing the elements' state only when necessary. For example, shrinking the progress bar only when it goes off screen and animating it when it comes back into view.

Here is a sample code snippet:

  var $animation_elements = $('.progressAnimation');

  $(window).on('scroll resize', function(){
    var viewportHeight = document.documentElement.clientHeight;

    $animation_elements.each(function() {
     var $el = $(this);
     var position = this.getBoundingClientRect();

     if (position.top > viewportHeight || position.bottom < 0) {
        this.inView && $el.css({ width: 0 });
      this.inView = false;
     } else {
        !this.inView && $el.css({ width: 6 * $el.data("percent") });
      this.inView = true;
     }
    });
  });

I have also optimized the event handler by incorporating vanilla Javascript for faster performance.

You can check out the working JSFiddle here.

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

Utilizing PHP Variables in an External JavaScript: A Step-by-Step Guide

I am attempting to utilize an array generated in PHP within my external JavaScript. My PHP code retrieves images from a directory based on the user ID provided via URL and stores them in an array. I aim to use this array in JavaScript to create a photo sli ...

Cross-origin resource sharing (CORS) issue encountered while trying to play an mp

I am facing an issue with my React application where it is unable to play audio from a different source due to a CORS error. Example: Interestingly, when I visit https://www.w3schools.com/tags/tag_audio.asp, input the above URL and click play, it works fi ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

What steps should be taken to activate eslint caching?

I'm attempting to activate eslint caching by following the instructions in this section of the user guide The command I am using is npm run lint -- --cache=true, and the lint script simply executes a script that spawns esw (which itself runs eslint â ...

Show different JSON data based on the existence of another key in Javascript

Having recently started learning JavaScript, I attempted the code below but couldn't quite get it to work. Despite consulting various resources, I still wasn't successful. Desired Output: To check if AUTO damage is present in the data. If so, re ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...

"What is the best way to use JavaScript to update several elements based on their class and incorporate distinct sub data for

Essentially, I am receiving a sequence of 5-10 events from an external server in the following format: event: add data: { "hostname":"name", "properties": {"info": "50"}} event: add data: { "hostname":"name2", "properties": {"info": "45"}} event: add da ...

The issue with MUI TextField: the outline is overlapping the label

Recently, I encountered an issue with a MUI TextField in my project. In its default state, everything appeared fine: https://i.stack.imgur.com/WFzOr.png However, when I increased the font size as per the theme provided below, the label started to overlap ...

Sending data to a modal within a loop

I am looking to modify the functionality of my current table setup. Currently, the table is generated by iterating through all the samples passed to it via the context in views.py of my Django app, and this setup is working well. However, I want to imple ...

Awaiting the completion of the AJAX request before wrapping up the jQuery

I'm troubleshooting a piece of jQuery code that is not working as expected: var newData = checkCP(somedata); if(newData=="hi"){ alert("Welcom"); } function checkCP(jsData){ $.ajax({ type: "POST", url: "Process.php", ...

Discover anew the means to revive JavaScript and Ajax call towards the controller without necessitating any user click within the captivating Razor View of MVC 4

Controller Action : public ActionResult googlemap() { return View(); } This specific controller action is responsible for rendering the "googlemap.cshtml" view. It makes use of Ajax calls and includes JavaScript code in the "googlemap.csh ...

Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown ...

What could be causing the malfunction of the dropdown menu attached to my button?

I've been working on setting up a simple button in my Angular application that should display a dropdown menu with various options when clicked. I copied and pasted some Bootstrap template code, made some modifications to match the style of my app, bu ...

Ways to give a z-index to create distance between an image and a div's border

Fiddle: https://jsfiddle.net/0qqnvrdg/ HTML: <div class="loading"></div> CSS: body { background: #0d8aa5; } .loading { position: absolute; left: 50%; top: 25%; /*margin: -60px 0 0 -60px;*/ background: #fff; width: 200px; ...

What is the process for integrating the neo4j-graphql library into a GraphQL API?

I am currently working on building a GraphQL API and have set up dummy data for testing purposes. My next step is to connect this GraphQL API to a Neo4j database using the neo4j-graphql library. Can anyone provide guidance on how to establish this connecti ...

Exploring the Advancement of Themes in Liferay

Struggling to create a Liferay 6.2 theme and feeling a bit confused. I started a new project, selected theme, clicked on next, chose velocity and _styled responsively. However, I actually want a standard theme that can be deployed without any changes comp ...

The jQuery window is not showing up as it was written in the code

This snippet of code is supposed to generate a dialog box, but instead, it only displays text with a CLOSE button. The code was sourced from the official Jquery website. <!doctype html> <html lang="en> <head> <meta charset="u ...

Using Vue Js to bind two values to an href attribute in a tag

As a Vue.js beginner, I am encountering an issue where I need to update two values simultaneously during rendering. <ul class="category-list"> <li v-for="category in categories"> <a v-bind:href="location/category.slug/all" v-tex ...

When hovering over A, the DIV element fails to appear

I'm encountering an issue with a specific page on my website () The problem lies with a .dropdown class that is supposed to display a DIV right below the header. In the source code, you can find it underneath <-- START DROPDOWN MENU -->. When I ...

What is the reason that a div can accept both before and after selectors, while an img tag cannot have this capability

What is the reason behind a div being able to accept before and after selectors, while an img tag cannot? How can I effectively define two pseudo elements for my image? ...