Fade in image only after finish loading - javascript

I've some images on a page which are loaded randomly and they are over 100kbs, is it possible to have it fully loaded then fade it in rather than progressively loading it?
My JS looks like this...
(function($){
$.randomImage = {
defaults: {
//you can change these defaults to your own preferences.
path: '_images/', //change this to the path of your images
myImages: ['hero_eagle.jpg', 'hero_giraffe.jpg', 'hero_owl.jpg', 'hero_rabbit.jpg']
}
}
$.fn.extend({
randomImage:function(config) {
var config = $.extend({}, $.randomImage.defaults, config);
return this.each(function() {
var imageNames = config.myImages;
//get size of array, randomize a number from this
// use this number as the array index
var imageNamesSize = imageNames.length;
var lotteryNumber = Math.floor(Math.random()*imageNamesSize);
var winnerImage = imageNames[lotteryNumber];
var fullPath = config.path + winnerImage;
//put this image into DOM at class of randomImage
// alt tag will be image filename.
$(this).attr( { src: fullPath });
});
}
});
})(jQuery);

Should be able to, just set the image to display:none in your stylesheet and modify the bit of the script that sets the src to this:
$(this).attr( { src: fullPath }).load(function() {
$(this).fadeIn()
});

Start with the images hidden using CSS. Then use:
$(document).ready(function() {
// Code goes here.
});
and have the fade-in execute there.
There's another SO question that discusses preloading images using jQuery right here: Preloading images with jQuery
Quoting from the top answer:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);

if you want all images to preload before fading in, and display a loading message to the user, you can use something like this:
var gotime = imgArray.length;
$(".maxCount").text(gotime);
var imgCounter = 0;
$.each(imgArray, function(){
$(new Image()).load(function(){
imgCounter++;
$(".presentCount").text(imgCounter);
if (--gotime < 1) {
$("#content").fadeIn();
}
}).attr('src', this);
});

Related

Javascript display dynamic changing image

I want to refresh an image every 1 second. This picture is dynamically generated by my webcam, but this script sometimes display broken images when browser didnt yet load a picture before display. How to detect when picture is loaded and then change the diplay picture?
I have a code like this:
<img id="image" src="webcam.jpg">
<script>
setInterval(function() {
var myImageElement = document.getElementById('image');
myImageElement.src = 'webcam.jpg?rand=' + Math.random();
}, 1000);
</script>
You should wait for the image to be loaded first, before replacing it.
For this, you can use different approaches. What I usually do, is to create another image which is not visible and replace the one visible once the previous image is loaded.
Your code should look like this if you want to follow this approach:
<img id="image" src="webcam.jpg">
<script>
setInterval(function() {
var url = 'webcam.jpg?rand=' + Math.random();
var img = new Image();
img.src = url;
img.addEventListener('load', function() {
var myImageElement = document.getElementById('image');
myImageElement.src = url;
});
}, 1000);
</script>
What you can also do is play with css styles to make the image hidden or visible depending on the state, but that would make your image appear and disappear which is a bit ugly...
I hope it helps :)
I think you can use something like this:
var _img = document.getElementById('pic'),
urlToImage = 'pic.jpg',
modified = false, lastModified = 0;
setInterval(function(){
fetch(urlToImage)
.then(function(resp){
var f = new File([resp],"file");
switch(true) {
case modified === false:
lastModified = f.lastModified;
modified = true; break;
default:
modified = false;
if(lastModified < f.lastModified) {
modified = true;
}
}
return resp.blob();
})
.then(function(blobdata){
switch(true) {
case modified === true:
var obj_url = URL.createObjectURL(blobdata);
_img.src = obj_url;
break;
}
});
},1000);
<img src="" id="pic" alt="LOCAL pic here"/>
I think that looking at lastModified time in File properties is a good way to assume image was finished written on the server.
Hope this helps.
Try using this after loading the document
$( document ).ready(function() {
setInterval(function() {
var myImageElement = document.getElementById('image');
myImageElement.src = 'webcam.jpg?rand=' + Math.random();
}, 500);
});
Hope this helps

Is this an efficient way to display an image using jQuery

This code works, but is it an efficient way to go about displaying an image once it has been loaded?
LightBoxNamespace.SetupLightBox = function(path, lightBox) {
// Create a new image.
var image = new Image();
// The onload function must come before we set the image's src, see link for explanation.
// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.
// Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
image.onload = function () {
if ($('#image').length) {
$('#image').attr('src', path); // If the element already exists, change the src to our loaded image.
}
else {
$('<img id="image" alt="">').attr('src', path).insertAfter('#close'); // If the element does not exist, insert the full image html into the lightbox.
}
LightBoxNamespace.CentreBoxInViewport(lightBox);
LightBoxNamespace.ShowOverlay(lightBox);
};
// Set the src, and show the image.
image.src = path;
};
var img = $('<img>');
img.load(function(){alert("image loaded!")});
img.attr('src', "url");
if (!! img) img.appendTo('#close');
http://jsfiddle.net/W57QR/4/
"The jQuery way":
var $img = $('<img/>').prop({ src: path });
$img.load(function() {
console.log('image loaded correctly');
$(this).insertAfter('#close');
}).error(function() {
console.log('error loading image');
});

Jquery Fade in background-image on dynamically created div [duplicate]

This question already has answers here:
Image preloader javascript that supports events
(4 answers)
Closed 3 years ago.
I've searched everywhere, but can't seem to find an answer to this... I'm looking for a way to check if a dynamically created div's background image has loaded.
I have built a photo gallery that first makes an ajax call and then creates divs with background images to display thumbnails of all the photos in the gallery. You can check it out here: http://www.aslamhusain.com/design.php#id=set_Allison_Basha
I would like to find a way to fadein each div when it loads, but I can't find a way to check if the background image has loaded. Is this even possible? Your help is much appreciated! First time posting here, this site has always been a lifesaver for me!! Thanks in advance,
Here is the code:
if($("#"+gallery_id).length<=0){
$.ajax({
url: "get_photos.php?gallery="+gallery,
success: function(data){
//create gallery div
$("#wrapper").append("<div class='page' id='"+gallery_id+"'><h2>"+gallery+"</h2></div>")
//sort ajax data
window.pic_array = data.split("***");
var total_images = window.pic_array.length - 1;
for(i=0;i<total_images;i++){
var pic_data = window.pic_array[i].split("|")
var date = pic_data[0] ;
var comment = pic_data[1];
var photo = pic_data[2];
var width = pic_data[3];
var height = pic_data[4]
var new_div = $("<div/>", {
id: "image_"+i,
class: "thumbnail_div",
click: Function("float_image('"+i+"')"),
css: {
backgroundImage: "url(thumbs/"+photo+")",
}
})
new_div.appendTo($("#"+gallery_id))
}
}
});
}
This plugin can be usefull. It provides useful callbacks once descendant images have loaded.
https://github.com/alexanderdickson/waitForImages
$('selector').waitForImages({
finished: function() {
// called once all descendent images have loaded
},
each: function() {
// will be called for each image that is loaded
},
waitForAll: true // To check for images referenced in the CSS (background-image, list-style-image, border-image, border-corner-image)
});
This is totally untested, but you might be able to do this like this:
var photo = pic_data[2];
var width = pic_data[3];
var height = pic_data[4];
var image = new Image();
image.src = "thumbs/" + photo;
image.onload = function() {
var new_div = $("<div/>", {
id: "image_" + i,
class: "thumbnail_div",
click: Function("float_image('" + i + "')"),
css: {backgroundImage: "url(thumbs/" + photo + ")"}
})
new_div.appendTo($("#" + gallery_id))
});

Javascript timed slideshow not working in the least

And it's saddening. Some background, I'm new to Javascript and this is my first application of in life, and since plowing halfway through half a Javascript textbook in two days. It's an external file that's linked to at the end of my HTML. If any more is required, please ask and I'll do my best to provide.
var slide = document.getElementById("slide");
setInterval(slideshow.changeSrc, 5000);
var slideshow = {
changeSrc : function() {
if(slide.src === "./images/s1.png"){
slide.src = "./images/s2.png";
}
else if(slide.src === "./images/s2.png"){
slide.src = "./images/s3.png";
}
else{
slide.src = "./images/s1.png";
}
}
}
slide.addEventListener("load", slideshow.changeSrc, false);
The src property is the result of the browser resolving the URL you give it. Do not use it for comparisons. In addition, only the window and certain elements such as images or scripts have load events. Try this:
Instead, why not just keep track of an index?
(function() {
var id = 0, slide = document.getElementById('slide');
setInterval(function() {
id++;
slide.src = "images/s"+id+".png";
id %= 3;
},5000);
})();
I think this is what you are trying to achive:
var slide = document.getElementById("slide");
var slideshow = {
changeSrc : function() {
setTimeout(function() {
slide.src = 'http://lorempixel.com/100/100';
}, 1000);
}
}
slide.addEventListener("load", slideshow.changeSrc, false);
http://jsfiddle.net/Bs4gM/

JS wait for CSS background image to load

It's easy to keep javascript waiting for some images to load if those are classic HTML images.
But I can't figure how to do the same if the image is loaded as a CSS backuground-image!
Is it possible?
The jQuery .load() method doesn't seem to apply.. and I'm short of ideas
It looks for elements with src attribute or backgroundImage css property and calls an action function when theirs images loaded.
/**
* Load and wait for loading images.
*/
function loadImages(images, action){
var loaded_images = 0;
var bad_tags = 0;
$(images).each(function() {
//alert($(this).get(0).tagName+" "+$(this).attr("id")+" "+$(this).css("display"));
var image = new Image();
var src = $(this).attr("src");
var backgroundImage = $(this).css("backgroundImage");
// Search for css background style
if(src == undefined && backgroundImage != "none"){
var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;
src = pattern.exec(backgroundImage)[1];
}else{
bad_tags++;
}
// Load images
$(image).load(function() {
loaded_images++;
if(loaded_images == ($(images).length - bad_tags))
action();
})
.attr("src", src);
});
}
One alternate approach would be to fetch the image data via AJAX as a base64 encoded png and apply it to the element's background-image property.
For example:
$.get('/getmyimage', function(data) {
// data contains base64 encoded image
// for ex: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
$('#yourElement').css('background-image', 'url("' + data + '")');
});
You will also need a server side script that reads the image, converts it into base64 encoded png (and cache it maybe) and return the same.
Try this one...
Its a jQuery-Plugin which gives you control to wait for images to be loaded
Project-Home
Thread # SO
Official way to ask jQuery wait for all images to load before executing something
Answer # SO
(ShortLink)
this is untested code but try this:
$(document).ready(
function()
{
var imgSrc = $('theTargerElement').css('background-image');
var imgTag = $('<img>').attr('src',imgSrc).appendTo( 'body' );
}
);
$(document)
.load(
function()
{
// do stuff
}
);

Categories

Resources