Display the preload.gif before the image finishes loading

I have a collection of images in a gallery and I want to assign a class name to all image tags, so that before they finish loading they show a preload.gif. Once the image finishes loading, it should display the actual image. I attempted to achieve this using the following code:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function myFunction() {
        alert("Image loaded: " + document.getElementsById("myImg").complete);
      }
    </script>
  </head>
  <body onload="myFunction()">
    <p>This property returns true if the image is finished loading, and false if not.</p>
    <img class="myImg" src="compman.gif" alt="Computerman" width="107" height="98">
  </body>
</html>

This code only supports the use of id names, but I would like to assign a class name to all image tags instead.

Answer №1

After experimenting with various methods, I finally found a solution that worked perfectly for me.

Initially, I displayed the loading gif as the image placeholder. Once the gif loads, a function is triggered to load the actual image. When the image is fully loaded, the function updates the source of the original image based on the provided parameters.

Here is the JavaScript code:

function loadimage(imgsrc, change){
  var loadimage = new Image();
  loadimage.onload = changesrc(imgsrc, change);
  loadimage.src = imgsrc;
}

function changesrc(imgsrc, change) {
  change.src=imgsrc;
}

For the HTML part (the linked photo is large to ensure loading indication):

<img onload="loadimage('http://upload.wikimedia.org/wikipedia/commons/4/49/Swiss_Jungfrau_mountains.jpg',this);" src="http://jimpunk.net/Loading/wp-content/uploads/loading2.gif">

This approach allows you to keep the original image source in the img tag itself, making it convenient and organized.

Answer №2

To add a loading spinner to your images, you can use the loading.gif as a background-image in your CSS class. Make sure to preload it or convert it to a base64 data-uri. This will display the loading spinner first before the actual image loads via its source.

<img class="gal" src="[your image URL]" />

.gal {
    width: 170px;
    height: 104px;
    background-image: url([your loading.gif])
}

See the demo here: http://jsfiddle.net/ygalanter/bv3Hd/2/

(Please remember to clear your browser cache if you want to re-run the demo).

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

When I implement JavaScript on my website, my HTML content does not show up

Whenever I try to fetch content from a specific URL using AJAX and a script, my HTML content does not show up. In other words, the table element is not displayed on the page. Instead, I am able to retrieve data from the specified URL and display it in an a ...

Change the text field's border color if the field is not empty

On my website, there is a TextField where users can enter values to perform a site search. My question pertains to the border color of this field. Normally, the border color is black when the field is not in use. However, when a user clicks on the field an ...

Stopping a function that is currently running on a website using Javascript

I have a script on my website that triggers a rain feature when a user clicks on a button. However, I am struggling to figure out how to allow the user to deactivate this feature. I've tried various methods such as using break, return, and timeouts, b ...

Resizing Navigation Bar in WordPress Theme WP Clarion

Struggling to enlarge the size of the navbar below and urgently need to have it done before tonight. I've reached out to the developers for support but still need to find a solution: Check out the site here: penarthpc.com/~nuvolaor/ Unfortunately, t ...

Tips for effectively integrating data from MongoDB into a React application

Currently, I am utilizing two components to extract data from the database. One component is used to loop through the data entries, while the second one is dedicated to accessing and displaying the details for each entry. Within my database, there is a fie ...

I had hoped for the search results to be displayed in neat columns, but unfortunately only the text is formatted that

I am working on a WordPress plugin that displays search results. Here is the PHP code for the results: <?php /** * Search & Filter Pro * * Sample Results Template * * @package Search_Filter * @author Ross Morsali * @link http://w ...

Tips for automatically displaying the scroll bar continuously on iOS 15 without requiring user interaction

We have a Web Application that displays a scroll bar for users to navigate through the content. The scroll bar functions correctly on desktop browsers and Android browsers, but not on Apple devices running iOS 15 (Safari Browser). Current Behavior : In ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

Nextjs: issue with updating state within an interval is not functioning

This is my current situation: const [time, setTime] = useState(10) And this is the function I'm using: const runTimer = () => { useEffect(() => { const interval = setInterval(() => { console.log(time) if ( ...

What is the most efficient way to define the font properties for all H1-H6 headings in a single declaration

Is there a way to set all font properties for H1-H6 headings in one CSS declaration? CSSLint.net is flagging multiple definitions of heading styles as an issue. I currently have specific styles for each heading level: h1 { font-size: 1.8em; margin-top: ...

Is it possible to pass multiple functions to the parent component in ReactJs if using OnChange() as a prop?

Just getting started with React and trying to pass data from a child component to a parent component. <div className="filter-module"> <i className="fas fa-sign-in-alt icon"></i> < ...

Element Proxy

I decided to experiment and see how a library interacts with a video element that I pass to it. So, I tried the following code: const videoElement = new Proxy(document.querySelector('video'), { get(target, key) { const name = typeof ...

Using Javascript within HTML: A guide on when to utilize semi-colons and when to implement the return false statement

Exploring the use of JavaScript attributes within HTML elements: <input type="button" onclick="somceFunc()" /> <input type="button" onclick="somceFunc();" /> <input type="button" onclick="somceFunc(); return false;" /> Debating whether ...

Displaying a PHP variable on the console through the power of jQuery and AJAX

I'm attempting to display the value of a PHP variable in the browser's console using jQuery and AJAX. I believe that the $.ajax function is the key to achieving this. However, I am unsure about what to assign to the data parameter and what should ...

What is the best way to remove column and row gaps in a Bootstrap grid system?

Despite adjusting padding with the image, div section, and grid gap to 0px in the grid layout, the image still fails to cover the entire cell. I am seeking a solution to eliminate these unwanted paddings that are highlighted in blue. The Bootstrap 5 .g-0 ...

What is the best way to integrate asynchronous computed observable with several concurrent $.ajax requests?

I'm currently working on implementing an asynchronous computed observable following the guide provided here. While I have successfully achieved this for a single ajax call, I am facing a challenge in figuring out how to perform multiple ajax calls in ...

Creating a website using the Hugo Tikva theme and Bootstrap-4 for a seamless and modern design

Embarking on a complete overhaul of my company's website, I've decided to utilize the Hugo framework and Bootstrap for the revamp. While web development isn't my expertise, I'm in need of guidance on how to effectively leverage a Hugo t ...

I attempted to pull information from the database and display it in my checkboxes. However, I encountered an issue where I am unable to save the selected checkboxes back to the database

This code snippet is written in Blade for a reservation form: <div class="col-lg-6"> <div class="contact-form"> <form id="contact" action="{{url('/reservatio ...

Using the .load() function to import an HTML file from the directory above

I am trying to achieve the following structure: folder1 index folder2 page to load Can I dynamically load the 'page to load' in a div within the 'index' page using DIV.load()? I have attempted various paths (../folder2/page, ./, ...

There seems to be a glitch in the AJAX code

I am currently working on a project that involves displaying categories and subcategories of products on a webpage. When users click on either a category or a subcategory, AJAX is used to send the selected item to a php script which then generates HTML cod ...