Execute js after all image loaded - javascript

(I searched, but not find exactly/easy solution)
I'm trying to execute JS after all images completely loaded. My goal is, when all images finish load completely, then removeClass my-loader and addClass visible to main-slider div.
HTML:
<div class='main-slider my-loader'>
<img src="/nice-girl.jpg">
<img src="/nice-car.jpg">
<img src="/nice-boy.jpg">
</div>
Execute below js when all images completely loaded
$(".main-slider").removeClass("my-loader").addClass("visible");
Tried :
But not work, problem is it execute before complete image load:
var imagesPre = new Array;
var success = new Array;
$('.big-slides img').each(function(){
imagesPre.push(this.src);
});
for (i = 0; i < imagesPre.length; i++) {
(function(path, success) {
image = new Image();
image.onload = function() {
success.resolve();
};
image.src = path;
})(imagesPre[i], success[i] = $.Deferred());
}
$.when.apply($, success).done(function() {
$(".main-slider").removeClass("my-loader").addClass("visible");
});
Any ideia for simple solution?

You can use load() to check if the images are loaded!
$('.imgTag').each(function(){
$(this).load(function(){
$(".main-slider").removeClass("my-loader").addClass("visible");
})
})
This may not work sometimes when the images are cached by the browser. Please check Caveats of the load event when used with images
var img = $('img')
var count = 0
img.each(function(){
$(this).load(function(){
count = count + 1
if(count === img.length) {
$('.main-slider').removeClass('my-loader').addClass('visible')
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main-slider my-loader'>
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
</div>
But, this answer is a working case.

<div class='main-slider my-loader'>
<img class="imgTag" src="/nice-girl.jpg">
<img class="imgTag" src="/nice-car.jpg">
<img class="imgTag" src="/nice-boy.jpg">
</div>
jquery codes:
`
window.loadCount = 0;
$('.imgTag').onload(function(){
window.loadCount++;
if(window.loadCount == $('.imgTag').length){
$('.imgTag').show();
}
});
`

Related

how to load images after everything else is loaded?

i got some idea that to load a fake image on a div before original image finishies loading and that to be after winodws load.i got some code but cant understand in which part i have to put src image for fake image and original image.do help me out in this code .
my html part is
<div class="myimage"><img src="myimage.jpg" /></div>
note:Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading........
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
You can use data attribute to do it:
<div class="myimage"><img data-orig="original.jpg" src="fake.jpg" /></div>
$(window).load(function(){
$('.myimage img').attr("src", $(this).data('orig')).removeAttr('data-orig');
});
You can add your images url to a custom data-url attribute and make your image url a base64 1x1 gif. And then when the page loads completely you can get your url from it. Basically it will be like this.
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="original-image.png" />
$(window).load(function() {
$("img").each(function() {
$(this).attr("src", $(this).attr("data-src"));
});
});

how to reduce load time of image in javascript

I am loading image on button click next and previous
here i have only 2 div which are animating on click of next and previous button with different images coming from database through json.
I am getting my functionality done but it looking fine only on localhost when I am uploading this on server it gets a blank screen between the animation due to image loading actually what happens my div has completed animation and showing next div but image are loaded properly so a blank div is shown
I want to reduce this load time or my screen will show when the image has been loaded completely how can I fix it ?
basically i want a ajax loader which will automatically get remove after loading
Here is my code
<table cellpadding="0" cellspacing="0" border="0" width="815" align="center">
<tr>
<td><div class="btnPrv2" id="btnPrv2"><</div></td>
<td>
<div class="slider">
<div class="mc3" id="mc3" ><img src="" class="ff3" /></div>
<div class="mc4" id="mc4" ><img src="" class="ff4" /></div>
</div>
</td>
<td><div class="btnNxt2" id="btnNxt2">></div></td>
</tr>
</table>
<script>
$(function(){
$(".mc3").animate({left:"-=782px" },350);
$(".mc4").animate({left:"-=782px" },350, function(){ curwdiv = hdiv; canAnim = true});
});
</script>
One way to do it could be load the images when loading the page but keep it hide it using zindex or something like that, then you just need to put it on front and the load time should be longer for loading the page but lesser on the button action.
Could be something like this in your html:
<div class="mc3" id="mc3" style="zindex:-1;" ><img src="" class="ff3" /></div>
And then something like this in your js to show the image (maybe in your function):
$(".mc3").zIndex(inherit);
PD: I think you should look into your ortography and sintax, it is nearly impossible to understand you question.
I've got this plug somewhere,
For example you have
<img class="preload_image" src="#">
<img class="preload_image" src="#">
<img class="preload_image" src="#">
It will count the images, and will check if all of them are already loaded, check the code below.
// .preload_image is the image class that needed to be loaded
$('.preload_image').imagemonitor({
'onLoad': function (loadedImage, totalImage) {
// While loading, progress bar will be shown
$('#load-progressbar img').css('width', Math.floor((loadedImage / totalImage) * 100) + '%');
},
'onComplete': function (loadedImage) {
// After loading, show image
$('#load-display').fadeOut(2000).queue(function () {
$('#content-display').fadeIn(2000);
$(this).dequeue();
});
}
});
Then here's the source code for that.
(function( $ ){
$.fn.imagemonitor = function(imageEvent)
{
var totalImage = 0;
var loadedImage = 0;
var loadedImageSrc = Array();
var imageObject = Array();
var isComplete = false;
var loop_delay = 200; // in miliseconds
var imgElement = this;
if(imageEvent.init == null) imageEvent.init = function(){};
if(imageEvent.onLoad == null) imageEvent.onLoad = function(){};
if(imageEvent.onComplete == null) imageEvent.onComplete = function(){};
function createImageObject()
{
imgElement.each(function(index)
{
imageObject[index] = new Image();
$(imageObject[index]).attr('src', $(this).attr('src'));
});
}
function count_loaded_image()
{
for(var i=0; imageObject[i]; i++)
{
if(!checkIfLoaded($(imageObject[i]).attr('src')))
{
if(imageObject[i].complete || imageObject[i].readyState === 4)
{
loadedImageSrc.push($(imageObject[i]).attr('src'));
loadedImage++;
imageEvent.onLoad(loadedImage, totalImage);
}
}
}
if((loadedImage == totalImage) && !isComplete)
{
isComplete = true;
imageEvent.onComplete(loadedImage);
}
else setTimeout(count_loaded_image, loop_delay);
}
function getTotalImage()
{
var tempImageSrc = Array();
imgElement.each(function(index)
{
var counted = false;
for(i=0; tempImageSrc[i]; i++)
{
if(tempImageSrc[i] == $(this).attr('src')) counted = true;
}
if(!counted) tempImageSrc.push($(this).attr('src'))
});
return tempImageSrc.length;
}
function checkIfLoaded(src)
{
var loaded = false;
for(var i=0; loadedImageSrc[i]; i++)
{
if(loadedImageSrc[i] == src) loaded = true;
}
return loaded;
}
function setOnloadEvent()
{
imgElement.each(function(index)
{
$(this).load(function()
{
if(!checkIfLoaded($(this).attr('src')))
{
loadedImage++;
loadedImageSrc.push($(this).attr('src'));
imageEvent.onLoad(loadedImage, totalImage);
if((loadedImage == totalImage) && !isComplete)
{
isComplete = true;
imageEvent.onComplete(loadedImage);
}
}
});
});
}
imageEvent.init();
totalImage = getTotalImage();
createImageObject();
setOnloadEvent();
count_loaded_image();
};
})( jQuery );

Condition to display image in Javascript

I'm looking for create a small javascript code to display images if their src is valid.
I have to separate the script to the html page for better organisation.
Here is what I did :
HTML
<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png" width="50px" height="50px" alt="" ;>
JavaScript
var thumbnail = document.images.thmb;
if(thumbnail.src)
{
if(thumbnail.onerror)
{
thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}
}
else
{
thumbnail.style.display = "none";
}
Bu it doesn't work, when I empty the src code in HTML, the border of the image still in the page. And if I write a wrong URL, we can't see the image set in the JavaScript.
Here is the JSFiddle to experiment it.
http://jsfiddle.net/gUb8X/
I'm a beginner in JavaScript.
Thank you !
You are too late with the test.
Try this
Live Demo
window.onload=function() {
var thumbContainer = document.getElementById("thmbDiv");
var thumbnail = document.createElement("img");
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}
Now replace your image with a div with id thmbDiv
if you put placeholders or hide all images you want to test, you can get the src from a data attribute.
Live Demo
window.onload=function() {
var imgs = document.images; // or document.getElementsByClassName("testImage");
for (var i=0, n=imgs.length;i<n;i++) {
var theImage = imgs[i];
var src = theImage.getAttribute("data-src");
if (src) {
theImage.onerror=function() {
this.style.display="none"; // or this.parentNode.removeChild(this);
}
}
theImage.src=src;
}
}
A neat inline solution would be this
DEMO http://jsfiddle.net/LstNS/25/
<img src="rando/path" id="image" onerror="this.style.display='none';"/>
jQuery:
You can use an ajax call to check if the image file exists
$.ajax({
url:'http://yourhost/someimage.ext',
type:'HEAD',
error: function()
{
//file does not exist
},
success: function()
{
//file exists do something here
}
});
DEMO http://jsfiddle.net/LstNS/24/
As you can see in the demo, the second image is not loaded and presented as a broken image as it does not exist.
A non jQuery version would be
var img = document.getElementById("myImg");
img.onerror = function () {
this.style.display = "none";
}
Your code now tests for thumbnail.src, which means that you are testing for the existence of an src propery, which always exists for a syntactically valid img element. Then you test for the existence of an onerror event handler, and since there is none, you take a branch that does nothing.
A way that works is to use an onerror attribute in the img element and make it remove the element (or remove it from rendering, but actually removing the element is more logical, and safer):
<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png"
width="50" height="50" alt="" onerror="rm(this)">
<script>
function rm(elem) {
elem.parentNode.removeChild(elem); }
</script>
Unfortunately, you can’t do this so with a loop that traverses through all img elements. If you try that, your code will run only after the image loading has been performed, so it would be too late to try to set onerror handlers on them.
I just found a little trick to make it possible. That doesn't follow the convention but it works. I just use the "alt" image keyword as the "src" keyword, and the JavaScript gives the src equals to alt attribute found in the html.
<img id="thmb" width="50px" height="50px" alt="http://blog.lefigaro.fr/bd/img-sanctuaire.png" ;>
Javascript :
var img = document.getElementById("thmb");
img.src= img.alt;
img.onerror = function () {
img.style.display = "none";
}
http://jsfiddle.net/LstNS/28/
To more, because I have to use a function to return all the final html code, I did this :
display: function (data) {
var pid = data.record.project_id;
var thb = data.record.Thumbnail;
var base_url = "<?php echo base_url('project');?>/";
function checkImg(){
try
{
var thumbnail = document.createElement("img");
thumbnail.src = thb;
} catch(err) {
//
}
if(thumbnail.height > 0){
var result = 'src="' + thb + '"';
}
else
{
var result = 'style="display:none;"';
}
return result;
}
return '<img id="thumbnail" ' + checkImg() + '" width="50px" height="50px" >';
}
I have to thank you for all your answers which permit me to find a good way to do it !
If you have comments to do, don't hesitate ! ;)

How do I exchange two images in a webpage (on two consecutive clicks) using jQuery?

I have two images among many that I want to swap places between. If I click on one image, then the other, the respective images should swap with each other and the rest should remain the same. I'm a beginner at this so any help or direction would be helpful.
This works also for every image:
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
JS
$(function(){
var src="";
var old;
$("img").click(function(){
if(src=="")
{
src=$(this).attr("src");
old=$(this);
}
else
{
old.attr("src",$(this).attr("src"));
$(this).attr("src",src);
src="";
}
});
});​
Another solution without any global variable.
html
<div id="images">
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
$('img').click(function(){
if($('#images img').hasClass('selected')){
var src = $(this).attr('src');
$('.selected').attr('src',src);
$(this).attr('src',$('.selected').attr('src'));
$(this).removeClass('selected');
}
else
$(this).addClass('selected');
});
Here is a different approach that swaps the actual elements rather than the src of the img, also avoids using external variables for the swap.
$('img.swap').on('click', function() {
var t = $(this);
if (t.hasClass('clicked')) {
t.removeClass('clicked');
return;
}
var clicked = $('img.swap.clicked')
if (clicked.length === 0) {
t.addClass('clicked');
return;
}
var placeHolder = $('<div id="placeholder"></div>');
clicked.before(placeHolder);
t.after(clicked);
placeHolder.before(t).remove();
clicked.removeClass('clicked');
});​
Example - http://jsfiddle.net/BxST9/3/ (using div instead of img but shouldn't make a difference)
See the example on: http://jsfiddle.net/Lvp4j/1/
var selected;
$("img").click(
function() {
if (!selected)
{
selected = this;
$(selected).addClass("selected");
}
else
{
var src1 = $(selected).attr("src");
var src2 = $(this).attr("src");
$(this).attr("src", src1);
$(selected).attr("src", src2);
$(selected).removeClass("selected");
selected = null;
}
}
);
My code adds also a selected class so you can highlight the clicked image...
try below code
html
<div>
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
(function() {
var swapArray = [];
var count=0;
$('img').click(function(){
count++;
swapArray.push($(this).attr('src'));
$(this).addClass(count);
if(count==2){
$('.1').attr('src',swapArray[1]).removeClass('1');
$('.2').attr('src',swapArray[0]).removeClass('2');
swapArray.length = 0;
count=0;
}
});
}());​
Given this HTML:
<img src="image_1.jpg" />
<img src="image_2.jpg" />
<img src="image_3.jpg" />
<img src="image_4.jpg" />
You could use the following JavaScript:
(function() {
var previous = null;
$('img').click(function() {
var current = $(this);
if (current.is(previous)) { // clicked same image twice; reset
reset_clicked();
} else if (previous != null) { // two images clicked; swap
swap_src(previous, current);
reset_clicked();
} else {
set_clicked(current);
}
});
function reset_clicked() {
previous.removeClass('clicked');
previous = null;
}
function set_clicked(img) {
img.addClass('clicked');
previous = img;
}
function swap_src(img1, img2) {
var src1 = img1.attr('src');
img1.attr('src', img2.attr('src'));
img2.attr('src', src1);
}
}());​
The 'clicked' class is added purely so you can use CSS to style clicked images. This class could also be used to identify any previously-clicked images, but I've used a JavaScript variable instead because that's quicker than a DOM lookup.
There's a demo on JSFiddle: jsfiddle.net/cvthL/2
This answer was posted as an improved version of Jitendra Pancholi's first answer and an alternative to his/her second answer.

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

Categories

Resources