Loading screen featuring animated sprites

I've recently started learning JS. I completed a few Lynda courses, but I'm struggling with creating an animated sprite preloader. I've searched extensively on Google and Stack Overflow, and although I found some helpful information, I haven't been able to achieve my desired result yet. Essentially, I have a logo set up as a sprite, and I want the sprite to animate based on the percentage of loaded files.

For example, from 0% to 15%, I want the first frame of the sprite to show, then the second frame between 15% and 30%, and so on until the last frame, at which point the div will be set to 'visibility:hidden'. This is how I envision it:

HTML

<div id="preloader">

CSS

#preloader {
margin: 0-auto;
width: 450px;
height: 400px;
background-color: #282727;
background-image: url(http://roprojects.net/preloader/sprite.PNG)
}

JS I'm not sure about the implementation, so forgive me if what follows sounds naive.

// var percent = Something that would get the numeric progress of the page load;
$( window ).load(function() {
// example of first animation. And I don't even know how I should be going on from here.
// Maybe a for statement, some sort of a loop, was even thinking conditionals. 
// Maybe a case/switch
// if (percent > 15 && percent <= 30) {below } 
  $('#preloader').css('backgroundPosition', '0 -400px');
});
// But ultimately that would require it to ..update itself (loop, I guess?)

This is my first post, thank you for your time and patience. Any external reference is also welcomed, not expecting you to write it for me. Again, thank you a lot!

edit adjust the sprite itself.

edit #2 After examining the preloader example at , I realized that a browser check is performed and upon successful loading, the preloader fades out to reveal the main content. However, I still need to figure out how to manipulate the sprite's animation based on the loading progress. The journey continues.

Answer №1

Swap out the i++ with your unique percentage code.
JS:

var i = 1;
setInterval(function () {
    if (i < 321) {
        i++;
    } else {
        document.getElementById("transparentImg").style.display = "none";
        document.getElementById("percentage").style.display = "none";
        document.getElementById("background").style.display = "none";
    }
    document.getElementById("percentage").style.width = i + "px";
}, 100);

HTML:

<div id="background"><div/>
<div id="percentage"><div/>
<img id="transparentImg" src="http://uniquewebsite.com/images/image.gif"/>

CSS:

body{
  background-color: navy;
}
#percentage{
background-color: rgb(255,200,200);
  width:320px;
  height:80px;
  margin-left:-150px;
  left:47%;
  margin-top:-40px;
  top:50%;
  position:absolute;
  z-index:1;
}
#background{
  background-color: rgb(120,120,120);
  width:320px;
  height:80px;
  margin-left:-150px;
  left:50%;
  margin-top:-40px;
  top:50%;
  position:absolute
}
#transparentImg{
  width:320px;
  position:relative;
  top:0px;
}

Answer №2

By exploring the Performance API using window.performance, you can access all the necessary data to enhance your loading graphics.

For beginners in JavaScript, starting with the performance API may be too complex initially.

Here are some simpler tools you can use:

  • requestAnimationFrame(yourFunction)
    : This function efficiently executes your animation loop when appropriate conditions are met, allowing for smooth image animations.

  • Event Listeners: Adding event listeners to resources can update your animation based on different events triggered during loading.

  • Canvas: For greater control over special effects and customization of images or sprites, canvas manipulation is recommended.

If you need inspiration for creating a loading animation using canvas, check out this example: http://jsfiddle.net/bbVTB/2/

Consider focusing on providing users with a sense of progress rather than displaying the actual loading time visually, as it can keep them engaged and curious about the outcome.

Avoid showing the loading time unless it becomes excessively long and causes user frustration. Instead, create an enjoyable distraction for users while they wait for the content to 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

"MongoDB scripting issue: Some documents within an array not being generated without any error messages

After creating a long array of documents, I am encountering an issue where not all the documents are being successfully created. const docsJson = [an array of JSON documents to create] const orders = await MySchema.create(ordersJSON); // The number of do ...

Access your account using AJAX for seamless login/logout functionality

I am attempting to incorporate AJAX functionality into my ASP.Net MVC application for user login and logout. Registering and logging in are successful, but once logged in, the page does not display the Welcome email or Logout link. Can someone point out wh ...

I can't seem to get my closure to function properly

My goal is to avoid cluttering the global namespace with multiple variables, but since I am unable to utilize 'let' at the moment, I am resorting to creating closures. I have a basic webpage layout that includes a bootstrap accordion with each ca ...

Having trouble triggering success or failure events when performing an ajax request

I am struggling to make a successful post request using a JQuery Ajax call. Even though the backend logs show that the file is uploaded, I can't get the success or error events to trigger. Adding console log statements to the success/error portions d ...

The impact of Ajax on jQuery document loading within an Ajax form

I'm currently using jQuery to change the colors of cancelled bookings in a Drupal view, and it's working well. jQuery(document).ready(function(){ jQuery(".bookingstatus:contains('Cancelled')").css("color","red"); }); However, when ...

Ensure the styling for the Range HTML Input Type is consistent and functional on both Chrome and Internet Explorer

I am facing an issue where the styling of a range type input field in my code is not compatible with IE11. try.html <div class="footer"> <div class="row justify-content-center"> <div class="container"> <input clas ...

Capture XMLHttpRequest request and manually send a 200 status response using vanilla JavaScript

After extensive research, I found conflicting information on this topic. I need to intercept an XMLHttpRequest and simulate a 200 status response from the backend using plain Javascript. This is specifically for testing purposes. So far, I have made pro ...

Wordpress: The success and error functions in ajaxSubmit options are failing to trigger

jQuery 1.7.2 jQuery Validate 1.1.0 jQuery Form 3.18 Wordpress 3.4.2 In my current coding environment with the jQuery libraries mentioned above, I'm facing an issue with the jQuery Form JS: I've adapted the code for ajaxSubmit from the developer ...

Loading data cards in Angular2 based on dynamic values from the database

I currently have a sample card designed using material design elements. How can I programmatically display multiple data cards based on the value stored in my database? For example, if the value retrieved from my mongoDB database is 4, then I want to dyna ...

angular directive for personalized data validation

I am trying to create a custom validation directive for my Angular app. The only issue I'm facing is figuring out how to retrieve a value. <select class="form-control" ng-model="$parent.newSector" ng-options="item.id as item.name for item in secto ...

Are the events objects failing to render or is the scope not being broadcasted properly

I'm having trouble displaying my events using the ionic-calendar plugin by calling the $scope.loadEvents method. Unfortunately, the events are not showing up on the calendar. Here is the link to the plugin I am using: https://github.com/twinssbc/Ioni ...

Why isn't Latex rendering when called from Javascript?

Below is the code I'm working with: function test() { document.getElementById('demo').innerHTML="$$\left[ x=0 \right] $$";//same code from demo1.but not rendered } test(); <script type="text/javascript" src="http://latex.co ...

The div tag is not being successfully added to another div tag using the append method

Can someone shed light on why the div with the button id is not being appended to the div having the clickable class in the code snippet below? var $el = $("<div/>", {class: "clickable",style: "margin:100px 10px 20px 20px ",}).append($("<div /> ...

Adjust the background color of the container when transitioning to a new slide in a Slick carousel

I am using a Slick slider where each slide has its own background color. The container color is set to white, but I want the container color to change instantly to match the color of the currently active slide when swiping or changing slides. This is my J ...

Incorporate the JavaScript SDK into your Vue project for enhanced functionality

I recently came across the ConvertAPI JavaScript SDK and decided to incorporate it into my Vue project. Following the installation process using npm: npm install --save convertapi-js I then proceeded to import and invoke it in this manner: <script> ...

What steps are needed to transform an HTML string into functional HTML code that will be visible on the front end of a website?

When using a v-for loop to iterate through items, the {{ item.data }} contains HTML elements with defined values. For example: The value of {{ item.data }} is a string "<'qr-code value="this has specific infos that is already created for this spec ...

"Receiving a 406 Error while attempting to retrieve a JSON object - Enc

A group of colleagues and I are facing an issue with an ajax call where the response is not what we expected. Instead of receiving a simple JSON object with different properties, the result.responseText value returns the HTML markup of a generic 406 status ...

Challenges with Implementing RTL Support in React Material UI Pagination Component

I've been trying to switch my pagination layout from left-to-right (ltr) to right-to-left (rtl), but the arrows are not aligning correctly in the rtl version. I attempted to use a solution provided here, but unfortunately, it didn't work as expec ...

How can we smoothly animate scrolling to the top of an element using jQuery?

I am attempting to implement a function where elements scroll to the top with animation upon being clicked. However, I am facing challenges in making this work successfully. You can view my code in action here: https://jsfiddle.net/3dqzsu2m/1/ Here is ...

Solving issues with the autocomplete feature in typeahead search through ajax calls

Currently, I am setting up a text input to function as a search box for retrieving search results through ajax calls with the assistance of the bootstrap typeahead plugin <form class="form-inline ml-3" action="/phone-autocomplete/"&g ...