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

The curly braces in AngularJS are not resolving as expected, however, the ng-bind directive is functioning properly

I'm currently working on a Django application and utilizing AngularJS for my frontend. I have a straightforward piece of code that looks like this: <div class="vert-carousel" ng-controller="PrizeController"> <div class="gallery-cell" n ...

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

Unlock the secrets of programming with the must-have guide to mastering variables

As a newcomer to the world of programming, I may be jumping ahead by asking this question too quickly. While reading a book, I came across something that confused me. Why is it necessary to create a variable for the password box element? Wouldn't the ...

Having trouble importing d3.js and typescript in IntelliJ?

Encountering errors in browsers' console when utilizing d3.select() in typescript code. Despite trying alternative methods like d3-timer.now(), the issue persists. As a newcomer to typescript, I am utilizing intelliJ Ultimate 2019.1. Through npm, I h ...

Nested setInterval in JavaScript refers to the practice of nesting

I am attempting to create nested timed code using setInterval. However, my initial approach does not produce any response from Chrome and Firefox: setInterval(function() { console.log('1'); setInterval(function(){ console.log(& ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

The styling of a CSS class in Internet Explorer may not be applied correctly if there are multiple elements sharing the same class name

For nearly a full week now, I've been plagued by a persistent issue! Here's the situation: I have 6 step tabs - step 1, step 2, and so on. Each tab has a CSS class called "locked" and "active." "Locked" - this style features top: 3em;, causing ...

Tips for eliminating extra blank space under the footer on an HTML website

Just beginning my journey with bootstrap and I am encountering an issue on my website where there is space after the footer when resizing to a mobile size. I've tried setting margin: 0; padding: 0; but it hasn't resolved the problem. Here's ...

jQuery .load() pause, content loading

Can anyone provide assistance with achieving the desired effect of fading out the #portfolio-wrapper, then loading the portfolio2.html and fading it in? Currently, the load function is executing before the fadeOut operation. Any help would be greatly app ...

A useful method to generate dynamic and random interval values for each loop of setInterval in NodeJs

I am trying to implement a feature where a function in nodeJS triggers another function at random intervals within a specified range. Each time the loop occurs, I want the interval value to be different and randomly generated between 3 and 5 seconds. bot ...

The JQuery code is failing to remove the dynamically added field when the delete icon is clicked

Information: I am currently navigating the world of programming and attempting to build a To-Do List feature. When the create list button is clicked, a dynamically generated div with the class 'wrap' is created. This div contains two nested divs: ...

Activate AngularJS autocomplete when populating the input field using JavaScript

I'm currently facing an issue with updating the value of an input field on a website using JavaScript. Although I can successfully update the input field's value, I find that I am unable to trigger the autocomplete feature. Interestingly, when ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

The most effective method for incorporating a header and footer into an HTML page utilizing a variety of client-side frameworks

Looking for a solution for my HTML project where I want to incorporate a header and footer to minimize rework. Any suggestions on a good approach? I have experimented with AngularJS using ng-include, and here is the code snippet: var app = angular.module ...

Issues with the functionality of the jQuery notify plugin are being encountered when used in a

I am currently utilizing the jQuery notify plugin and have included all the necessary JS files in the header. However, whenever I attempt to call the $.notify function in another JS file that also involves AJAX, I encounter difficulty accessing the $.notif ...

Ways to display and modify chosen and not chosen categories on the product editing page

I have three tables Categories: cat_id ... other ... primary key (cat_id) Product: Product_id ... other ... primary key (Product_id) Product_cat: Product_id foreign key (post.Product_id) cat_id foreign key (Categories.cat ...

Using Angular 2 to toggle visibility based on a select box's value

<div class="form-group"> <label class="col-md-4 control-label" for="is_present">Is Present?</label> <div class="col-md-4"> <select id="is_present" name="is_present" class="form-control" *ngIf="candidates.is_present === tr ...

ToggleButtonGroup in Material UI is a great way to create toggle

I am trying to implement the ToggleButtonGroup feature from Material UI in my React application. I am facing an issue where I am unable to pass values into my state correctly. The code snippet provided below shows that while the Select component works fi ...

Implementing fetch API in middleware in Next.js

Currently, I am utilizing a middleware in Next.js (https://nextjs.org/docs/advanced-features/middleware) for my project. However, I am encountering an issue when trying to send a request to the API. The error message displayed is: "unhandledRejection: Ty ...