The loading bar animation doesn't begin at a blank slate

I'm currently working on a project that utilizes Django for the backend and Bootstrap for the frontend. I have to admit, I am quite inexperienced when it comes to front-end development; JavaScript seems like magic to me.

One of the key features I need is an animated loading bar that smoothly progresses from 0% to 100% within a specified duration. Although I was able to create something that functions most of the time, there is a persistent issue.

The loading bar does not consistently start at 0%. It appears to start at random points, with occurrences where it even begins at 100%. This loading bar is situated within a modal window that pops up when the user clicks a button.

Following a helpful hint from Boris K, the main query seems to revolve around how to initiate the JavaScript function as soon as the modal window opens.

Below is an example snippet from an HTML file:

<div class="modal fade" id="scanBanknote" data-backdrop="static" tabindex="-1" role="dialog"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">Scanning banknote</h5>
            </div>
            <div class="modal-body">
                Please wait...
                <div class="progress">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var loading_time = 8
</script>
<script src="{%static 'js/progress_bar.js'%}"></script>

Contents of progress_bar.js:

// The loading time must be specified in milliseconds by multiplying it by 1000
var loading_time = loading_time * 1000
$(".progress-bar").animate({width: "100%"}, loading_time);

Answer №1

The animation currently triggers directly when the page loads, starting when the modal is still hidden. To improve this, trigger the animation when the modal is shown.

For information on different events for modals, refer to the Bootstrap documentation.

In this case, I used:

shown.bs.modal

This event occurs when the modal becomes visible to the user (after CSS transitions have completed). If triggered by a click, the clicked element can be accessed using the relatedTarget property of the event.

var loading_time = 8;

// loading time must be set in milliseconds, multiply by 1000
var loading_time = loading_time * 1000;

$("#scanBanknote").on("shown.bs.modal", function (event) {
  $(".progress-bar").animate({width: "100%"}, loading_time);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fdbfb0afbfbaadf1b5acb79db6bdbab7bdd791bcadadb2bd8ebbb6bd">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#scanBanknote">
  Click Me
</button>

<div class="modal fade" id="scanBanknote" data-backdrop="static" tabindex="-1" role="dialog"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">Scanning banknote</h5>
            </div>
            <div class="modal-body">
                Please wait...
                <div class="progress">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
                </div>
            </div>
        </div>
    </div>
</div>

If you're finding it challenging to understand in a different context, here's how things may look when applied to your scenario:

<div class="modal fade" id="scanBanknote" data-backdrop="static" tabindex="-1" role="dialog"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">Scanning banknote</h5>
            </div>
            <div class="modal-body">
                Please wait...
                <div class="progress">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="{%static 'js/progress_bar.js'%}"></script>
<script>
    $("#scanBanknote").on("shown.bs.modal", () => initProgressBar(8));
</script>

progress_bar.js

function initProgressBar(loading_time) {
    // loading time must be set in milliseconds, multiply by 1000
    loading_time *= 1000;
    $(".progress-bar").animate({width: "100%"}, loading_time);
}

Answer №2

Make sure to click on the "Run code snippet" button below. The progress bar will always begin at 0%.

The animation may start when the page loads, but since the modal is hidden, it won't be visible until you open it.

If that's the case, remember to trigger the $(".progress-bar").animate function only when the modal is opened.

var loading_time = 8
loading_time = loading_time * 1000

$(".progress-bar").animate({width: "100%"}, loading_time);
.progress-bar {
  height: 10px;
  background: red;
}

.progress {
  width: 500px;
  background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="progress">
  <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
</div>

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

Create and adapt dynamic tiles to fit within the available width

I am looking to create a dynamic tile (div) that adjusts based on the number of users available, similar to how it works in Microsoft Teams meetings. For example, if there is only one user, the div should occupy the full screen. When there are two users ...

Enhance your JavaScript code by replacing Promise syntax with Async syntax and utilizing map() instead of a traditional For

I have a code snippet here that is functioning properly. However, I am interested in converting the Promise code in the middle of the function to Async code and replacing the for loop with map(). Can someone guide me on how to achieve this transformation ...

Error message: "Uncaught TypeError: Cannot read property 'module' of undefined when using AngularJS in conjunction with RequireJS."

Embarking on my journey of app development with angularJS was a thrilling experience. However, after investing weeks into the project, I had an epiphany - why didn't I start using require JS from the get-go to load my modules? A rookie mistake, yes, b ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

What is the recommended method for writing JavaScript scripts with AJAX in a Rails application? How can URLs be incorporated into the script effectively?

When incorporating AJAX into my Rails application, I encounter difficulties when specifying the URL for the request within a script. While it is recommended to use helpers like my_resource_path instead of manually writing paths, these helpers do not functi ...

Tips for simplifying a JavaScript function

Hello everyone, I just joined StackOverflow and I could really use some assistance with a JavaScript and jQuery issue that I'm facing. Can someone suggest a more efficient way to write the code below?: jQuery(document).ready(function () { $("#ar ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

Maintain the state of the toggle div after page refresh or modification

In this scenario, I am looking to ensure that my div remains open even if the page is changed or refreshed. Below is the HTML and JavaScript code provided: You can view the working code here: http://jsfiddle.net/wasimkazi/fauNg/1/ $(".widget2").hide( ...

Altering content using jQuery

Trying to create a dynamic quiz using HTML, CSS, and jQuery. I am having trouble changing the <p id=question></P> element with jQuery code as nothing happens. Below is my HTML and jQuery code: <!DOCTYPE html> <html lang='es' ...

What is the best way to evaluate user input against a string retrieved from process.stdin.on()?

I'm having trouble comparing a string with user input from process.stdin.on as it always returns false. //Let's say the user inputs 'hello' every time. process.stdin.on('data', userInput => { let text = userInput.toStrin ...

Is there a way to showcase a single HTML canvas across multiple div elements?

I'm currently developing a web application that includes a Google Maps feature in two different tabs using Twitter Bootstrap. I am exploring options to have one canvas element that can be displayed in both tabs with varying dimensions. One idea is to ...

When Vuejs removes an element from an array, it may not completely erase it from the

Trying to execute the code below, I encountered an issue where removing one item from the array did not completely remove it (other checkboxes in each row remained). I attempted using :key="index" but that did not solve the problem. However, changing :key= ...

What is the best way to update the content of a particular div and its associated link ID whenever the link is clicked?

I need to update the content of a div by clicking on an href link that includes an id named data. The issue I'm facing is that I can't access the id value within my script because it's passed within a function. How can I pass the data variab ...

The button component in my React application is not functioning as expected, despite utilizing the useState and useEffect hooks

I'm having trouble with my Button not working, even though I am using useState and useEffect Check out the code below: import React, { useState, useEffect } from "react"; // import Timeout from "await-timeout"; import ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

How should endpoint functions be correctly written for Mongoose in conjunction with Express?

While developing the backend API for my app, I have come across numerous examples of different approaches to handling errors in endpoint functions. The two options presented below illustrate this: Option 1: export const deleteProject = asyncHandler(async ...

Guide on redirecting to a specific tab data target in Symfony 5

When a user is on the 3rd tab and clicks on a DELETE button, I want to redirect the user back to the same 3rd tab on the page. **Template:** <nav> <ul class="nav nav-tabs"> <li class="nav-item"> ...

JavaScript conditional statement malfunctioning

I am currently facing an issue with my JavaScript script. I am using jQuery to send data via AJAX to a PHP file and expecting a text dataType in return so that I can test it with JavaScript. My objective is to redirect the user to another webpage if the t ...

Revamping the values attribute of a table embedded in a JSP page post an AJAX invocation

I am encountering an issue with displaying the content of a table. The table's data is retrieved via an AJAX request when clicking on a row in another table on the same page. Here is my code for the JSP page: <table id="previousList" class="table" ...