Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the loader only appears upon clicking a button and is positioned at the top of a specific div.

I am striving to recreate the loading experience seen when logging into Google, where a progress bar animates at the top of the page. To achieve this functionality, I initially tried using pace.js. However, I am open to exploring other libraries that offer more customization options to solve this problem effectively.

function createDiv(event) {
  event.target.disabled = true;
  var html = '';
  html += '<div id="paceProgressBarBox" style="background:#ccc;width:200px;height:200px;"></div>';
  $('#myDiv').append(html)
  // add pace progress bar at the top of id="paceProgressBarBox"  and stop pace progress bar loading on browser referesh // instead show pace progress bar on click of button
  var pace;
  pace.options.target = '#paceProgressBarBox';
  pace.start();
}
.pace {
  -webkit-pointer-events: none;
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

.pace-inactive {}

.pace .pace-progress {
  background: #2299dd;
  position: relative;
  z-index: 2000;
  right: 100%;
  width: 100%;
  height: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.js">
</script>
<br/>
<button onclick="createDiv(event)">Change Content</button>
<div id="myDiv" style="width:200px;height:200px;"></div>

Answer №1

In pace.js, the progress bar is initially attached to the <body> element by default.
However, you have the option to change this by using the undocumented target setting.

There are two ways to specify the target:

  1. Create a paceOptions variable before loading the pace script:

    paceOptions = {
      target: '#myDiv'
    }
    

    Example with CSS styles:

    #myDiv {
          width: 200px;
          height: 200px;
        }
    
        .pace .pace-progress {
          position: relative;
          background: #2299dd;
          z-index: 2000;
          right: 100%;
          width: 100%;
          height: 5px;
        }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
    
        <script>
          paceOptions = {
            target: '#myDiv'
          }
        </script>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.js">
        </script>
    
        <button>Change Content</button>
        <div id="myDiv"></div>

  2. Specify the target in the <script> tag for the progress bar:

    <script src=".../pace.js" data-pace-options='{ "target": "#myDiv" }'></script>
    

    Example with CSS styles:

    #myDiv {
          width: 200px;
          height: 200px;
        }
    
        .pace .pace-progress {
          position: relative;
          background: #2299dd;
          z-index: 2000;
          right: 100%;
          width: 100%;
          height: 5px;
        }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.js" data-pace-options='{ "target": "#myDiv" }'>
        </script>
    
        <button>Change Content</button>
        <div id="myDiv"></div>


Additional resources:
Pace Configuration
Specify Location of Indicator


Edit:

To prevent Pace from automatically starting on page load, set the startOnPageLoad setting to false:

jQuery('#changeContent').on('click', createDiv);
#myDiv {
  width: 200px;
  height: 200px;
}

.pace .pace-progress {
  position: relative;
  background: #2299dd;
  z-index: 2000;
  right: 100%;
  width: 100%;
  height: 5px;
}

#paceProgressBarBox {
  background: #ccc;
  width: 200px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<script>
  var paceOptions = {
    'startOnPageLoad': false,
    'target': '#paceProgressBarBox'
  }

  function createDiv(event) {
    event.target.disabled = true;
    var $progBarBox = $('<div>', {
      'id': 'paceProgressBarBox'
    });
    $('#myDiv').append($progBarBox);
    Pace.start();
  }
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.js">
</script>

<button id="changeContent">Change Content</button>
<div id="myDiv"></div>

Check out these links as well:
Pace's source code for more options
How to stop Pace JS plugin from running on page load

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

Guide to attaching and displaying an image on a Three.js map

Currently, I have a 3D map loaded with three.js that includes mouse interaction. I've managed to place an image on the map using absolute positioning, but unfortunately, as I move the map around, the image stays stationary. Does anyone know how I can ...

Prepare for a thorough cross-referencing session

In my attempt to create a tool with 3 inputs that are interdependent - "Earn %", "Earn $" and "Own Price". Initially, the default value for "Earn percentage" is set at "10", making the initial calculation function as intended. Changing this one value auto ...

Tips on achieving horizontal scrolling for div overflow instead of wrapping onto a new line

It's a frequent occurrence in mobile apps to have a navbar with selectable text options that overflow horizontally without breaking into a new line. Instead, users must scroll horizontally to access all the options available. Is there a way for me to ...

The CSS focus-within and hover properties are not functioning as expected

How can I make the search tags visible (the buttons above the text input field) when the search bar below them is clicked? I've tried using :hover, :focus, and :focus-within, but none of them seem to be working. Can someone help me figure out the issu ...

How can we alert users when data has been updated without the need for a page

The following code was authored by me: $('.actionButton').click(function(){ var buttonValue = $(this).val(); var userId = '<?php echo $_SESSION['id']; ?>'; console.log(userId); ...

Using Angular service worker to pre-fetch video files

Issue arises when the service worker prefetches the entire video embedded on the page, leading to performance problems. My ngsw-config.json only contains configurations for local files, whereas the video is located on a different subdomain under /sites/def ...

jQuery - Discovering the MAC address in a string and potentially styling it

One challenge I'm facing on my website is the ability for users to input data, which often includes a MAC address. To streamline this process, I am looking for a way to automatically identify and reformat any MAC addresses that are entered in a delimi ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

An HTML attribute that functions like autofocus in the select tag

Is there a way to set the default focus on a select tag in HTML, similar to how autoFocus works for textboxes? I am looking to make a select tag automatically focused when the page loads. Is there a method to achieve this? ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

To view the previous or next image, simply click on the links and watch as the new image fades in seamlessly while maintaining

Whenever I click on a prev/next link, a specific div loads different images that loop. The JavaScript successfully changes the image source when the prev or next button is clicked. It works flawlessly. However, I am facing an issue. I want each new image ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...

The behavior of -webkit-border-radius differs from that of -moz-border-radius

My website is displaying differently on Safari compared to Firefox. I want the CSS to make it look consistent across both browsers. I understand that I could use two div boxes - one for the outline and one for the image. However, I prefer how Firefox only ...

What is the process for setting up redux in _app.tsx?

Each time I compile my application, I encounter the following error message: /!\ You are using legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). Although my application functions correctly, I am unsure ...

What is the best way to delete rows from a table that was created using a JQuery AJAX response?

I am currently working on a coding project where: The user is required to input a location, Clicks on a button to execute a GET call in order to fetch data based on the specified location, and A table is then filled with the retrieved data. My goal is t ...

Embedding PHP script within HTML code can enhance website functionality and

I am completely new to PHP and have never worked with it before. I'm interested in running a PHP script from within an HTML file on a Linux system. Can anyone guide me through the process? Below is the code from my HTML file: <!DOCTYPE HTML PUBLI ...

The absence of the dark class in the body is still allowing the impactful influence of Tailwind

I set up a ThemeContext in my NextJS project to switch between light and dark themes on my website. However, I encountered an issue where elements that have the "dark:" prefix in their class names apply the dark theme instead of the initial light theme whe ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...