The image will remain hidden until it is fully loaded and ready to be displayed

I am currently working on a script that involves displaying a loading icon until an image is fully loaded, at which point the loading icon should disappear and the image should be shown.

Unfortunately, my current code is not working as intended. Here is a snippet of it:

HTML

<script src="jquery/jquery-1.9.1.js"></script>
<script src="loading.js"></script>
<link rel="stylesheet" type="text/css" href="loading.css"/>

<body>    
    <img id="image" src="http://www.hdwallpapers3d.com/wp-content/uploads/car11.jpg"/>
    <img id="loading" src="loading.gif"></img>
</body>

jQuery

if ($("#image").ready()) {
    // code
    $("#image").show();
} else {
    $("#image").hide();
}

if ($("#image").ready()) {
    // code
    $("#loading").hide();
} else {
    // code
    $("#loading").show();
}

CSS

#loading {
    width:200px;
    height:200px;
}

Check out this fiddle for more details

Answer №1

Check out this code snippet:

<script>
    function LoadImage($this){    
     $($this).show();
     $('#loading').hide(); 
     console.log('image loaded');

}    
</script>
<img id="image" src="http://www.hdwallpapers3d.com/wp-content/uploads/car11.jpg" style="display:none;"  onload="LoadImage(this)"/>
<img id="loading" src="http://sierrafire.cr.usgs.gov/images/loading.gif"></img>

See the demo here: http://jsfiddle.net/TPbU8/1/

Answer №2

Take a look at this:

html code:

<div class="spinner"></div>
<img id="picture" src="http://www.hdwallpapers3d.com/wp-content/uploads/car11.jpg"/>

Css styling:

.spinner {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('http://sierrafire.cr.usgs.gov/images/loading.gif') 50% 50% no-repeat rgb(249,249,249);
}

javascript function:

 $(document).ready(function(){
   $(".spinner").fadeOut("slow");
 });

View the live example here: Demo

Answer №3

I've made some adjustments to your code snippet for it to function properly:

http://jsfiddle.net/TPbU8/3/

if ($("#image").ready()) {
// Updated code
    $("#loading").hide();
    $("#image").show();
}

Note: When working with jQuery, remember to include the jQuery library. Also, to prevent cached images from displaying, I have appended a random value at the end of the image URL.

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

Why Isn't the Alert Triggering Even Though the Routes are Set Up Correctly in jQuery?

Here's the Setup: <!DOCTYPE html> <html> <head> <title></title> <script src="jquery-2.1.1.min.js"></script> <script src="script.js"></script> </head> <body> <h1>I ...

Navigate between links by using the Tab key, while excluding certain links from the sequence

On my webpage, I have a main menu, various links in the main content area, and a left menu. The challenge is to make the website accessible for people who are blind... When using the tab button to navigate between links, the order currently goes as follow ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

Could not locate the express.js file

Currently in the process of learning express/node.js, but struggling to locate the page at localhost:3000/info You can view screenshots of my code below ...

Error: The method of promise.then is not recognized as a function

Having an issue with Rxjs v5 while attempting to run http.get requests one after the other in sequential order. The error message received is TypeError: promise.then is not a function. Below is the code snippet in question: var http = require('ht ...

Guide on aligning a division within another division?

Included below is my HTML code: <div id="background_div"> <img id="background_img" src="images/background.jpg" alt="dont matter"> <i class="material-icons">perm_identity</i> <div id="dropdown"> <ul id=" ...

Looking to retrieve a JavaScript code block from an AJAX response using jQuery?

How can I extract a Javascript code block from an ajax response using jQuery, while disregarding other tags (in this case, the div tag) and prevent the execution or evaluation of the Javascript code? Example in get_js.html: <script> $(function ...

Choose a selection from the options provided

This is a sample for demonstration purposes. I am trying to display an alert with the message "HI" when I click on Reports using the id main_menu_reports. My attempted solution is shown below. <ul class="nav" id='main_root_menu'> & ...

Conceal an element within the initial row of the table

Below is the table structure: <table id="mytable"> <tr> <td>name</td> <td> <a id="button1" class="button">link</a> </td> </tr> <tr> <td>name2</td> ...

How to Position an Input Text Beside an Icon Image Using JqueryMobile

Just starting out with jquery mobile and css! Check out my jsfiddle.net/mapsv3/kWJRw/1/, when I use an icon on the left side, the input text gets cut off and I can't see the end of it. ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

What is the method for creating a transparent background for Material UI v1.0 Dialogs?

I'm attempting to place a CircularProgress component inside a dialog box. However, I'm facing an issue where the background of the dialog box is white and cannot be set to transparent like in previous versions of Material UI (v0.2). style={{ ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

How AngularFire automatically adds back a removed item in a Firebase array

I have been working on a way to remove an item from my $firebaseArray called "boxes". Here is the "remove" function: function remove(boxJson) { return boxes.$remove(boxJson); } Although it gets removed, I noticed that it immediately reappea ...

Can you explain the distinction between document.body.ononline and navigator.onLine?

Can you explain the distinction between document.body.ononline and navigator.onLine? Do they utilize the same JavaScript API for checking network connectivity status (online/offline)? I have searched on Google but couldn't find a definitive answer. If ...

Issues with jQuery focus function in Internet Explorer 11

Is there a way to set the focus on an anchor tag using the URL? Anchor Tag: <a id='714895'>&nbsp;</a> URL: jQuery Code: try { if(document.URL.indexOf("?ShowAllComments=True#") >= 0){ var elementClicked = "#" +location.hre ...

What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame? var is_array = function (value) { return value && typeof value === 'object&apos ...

Is it possible in ReactJS to return JSX from a callback function?

After spending some time working with react, I encountered a basic issue that has me stumped. In the Login component, I am submitting a form and if it returns an error, I want to render a snackbar message. handleSubmit = (event) => { event.preven ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...