I have this html: <img src="myimage.jpg" id="idimg">
Is there a way with javascript to change that src to my ajax.gif
until the image is fully loaded?
Please note i have already watched here: How to display a wait gif until image is fully loaded
but i don't want that because I want my initial html to be as I wrote there (with the src of the original image) and not with a fake div container
thx
I have this html: <img src="myimage.jpg" id="idimg">
Is there a way with javascript to change that src to my ajax.gif
until the image is fully loaded?
Please note i have already watched here: How to display a wait gif until image is fully loaded
but i don't want that because I want my initial html to be as I wrote there (with the src of the original image) and not with a fake div container
thx
Share edited May 23, 2017 at 11:52 CommunityBot 11 silver badge asked Mar 25, 2011 at 16:23 anonanon5 Answers
Reset to default 4Using the same theory, you could have 2 images in the HTML source, one as the ajax.gif loader, and one as the actual image you are planning to show. Using css make sure only the loader displays on page load, and then attach an onload event to the actual image. When it is triggered you could then fade between the two.
This being said, I am not sure of the patibility of an image onload event in IE off of the top of my head.
Suposing that there is an image loading.gif in the 'Imagens' folder on the root.
js:
$('img').css('opacity', function () {
$(this).wrap("<div class='img-loading'></div>")
return '0';
}).load(function () {
var img = $(this);
$(this).unwrap();
$(this).animate({
opacity: 1
}, 500);
});
css
.img-loading {
background: url('/Imagens/loading.gif') 50% 50% no-repeat;
}
In jQuery you could do something like this:
$('your_img_selector').attr('src', 'ajax.gif'); //just change your img by the ajax.gif without any treatment
var img = $(new Image()); //create a new jQuery image object
img.load(function()
{
$('your_img_selector').after(this); //append the new object to your img
$('your_img_selector').remove(); //remove your img, so it continue as if as your img was simply changed ;)
}).attr('src', 'the_image_you_want_to_be_shown_after_ajax_loading');
I didn't test this code, but that is one idea I've implemented on a system, so I know it works ;) I don't know how to do in pure javascript, but I think it's not too different from this. At least the idea ;)
It hopes to be useful! :D
Set the background
property of the <img>
tag in CSS to be your loading GIF. You will need to set the width
and height
on the image for this to work properly. E.g.:
HTML
<img src="yourBigImage.jpg" width="1200" height="800" />
CSS
img {
background: url("loading.gif") 50% 50% no-repeat;
}
not sure if this is what you wanted but I think its pretty useful anyway. The code below will fade the load class in and out when loading Ajax.
$('.load').ajaxStart(function () {
$(this).fadeIn();
});
$('.load').ajaxStop(function () {
$(this).fadeOut();
});