I have 2 images. My intention is when the image finished display, and finished fade in, I will load some function.
My question
How do I make sure my image is fully loaded and displayed on screen?
I ask because sometimes, when the image is still loading (like only half the image is showing), it will fade in somehow, I need make sure it shows the full image before fading in.
FIDDLE
var temp = "";
var displaythumbnailbox = $(".area1");
var lis = $(".area1 img");
//hide the image , in order to use fadein
lis.hide();
lis.each(function(i) {
$(this).fadeIn('fast', function() {
console.log("finish load all image");
if (i == lis.length - 1) {
//getting last image display.
alert("finish display the last image");
//going to put some function here.
}
});
});
You can substitute css display:none for .hide(), .ready() , .promise()
css
.area1 img {
display:none;
}
javascript
$(document).ready(function() {
var temp = "";
var displaythumbnailbox = $(".area1");
var lis = $(".area1 img") //.hide()
.each(function(i) {
$(this).fadeIn("fast", function() {
console.log("finish load all image");
});
});
lis.promise().then(function() {
alert("finish display the last image");
})
})
jsfiddle https://jsfiddle.net/88ft369z/3/
If you want to display images in sequence you can substitute i multiplied by a duration, e.g., i * 250 at .each() for "fast" jsfiddle https://jsfiddle.net/88ft369z/4/
You can check if the element is loaded using .load().
var lis = $(".area1 img");
lis.load(function(){
lis.hide();
lis.each(function(i) {
$(this).fadeIn('fast', function(){
console.log("finish load all image");
if(i == lis.length -1)
{
//getting last image display.
alert("finish display the last image");
//going to put some function here.
}
});
});
Related
I am trying to change the src attribute in an img tag in html using jquery, I want scr attribute to change differently depending on the number of times the user has hovered over the img element.
My html is set up as follows:
<img id="element" src="img1.png">
My js/jQuery is set up as follows:
var count = 0;
if(count == 0){
$("#element").hover(function(){
count++;
$("#element").attr("src","img2.png");
}, function(){
$("#element").attr("src","img1.png");
});
} else if(count>=1){
$("#element").hover(function(){
count++;
$("#element").attr("src","img3.png");
}, function(){
$("#element").attr("src","img1.png");
});
}
The hover function on its own works fine, and hovering in and out will switch between two images. However, my goal is to make it switch to img2 in the first hover, and then img3 at the second hover, and thereafter. My hover function seems to work fine if I want it to hover between img1 and img2 or img 1 and img3, that is when I remove if statement and count variable.
If someone could help identify my problem please.
You need to do the counter check within the hover handler
var counter = 0;
$("#element").hover(function() {
$(this).attr("src", ++counter > 1 ? '//placehold.it/64X64/00ff00' : '//placehold.it/64X64/0000ff');
}, function() {
$(this).attr("src", "//placehold.it/64X64/ff0000");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="element" src="//placehold.it/64X64/ff0000">
In your code the value of counter is checked only once on page load where the value of counter is always 0
From what you've posted, if(count == 0) occurs in your setup code. None of your hover event handlers touch the value of count, so once the handlers are set (either to 1 and 2 or 1 and 3), they will never be changed. And since count is always zero when the handlers are added, you always get the first pair.
Instead, you should switch between the two images inside of your handler function, not in the code that assigns the handler.
Try creating array of strings containing img src , utilizing Array.prototype.reverse() to toggle images
var imgs = ["img2.png", "img3.png"];
$("#element").hover(function() {
$(this).attr("src", imgs[0]);
imgs.reverse()
}, function() {
$(this).attr("src", "img1.png");
});
var imgs = ["http://lorempixel.com/100/100/sports", "http://lorempixel.com/100/100/cats"];
$("#element").hover(function() {
$(this).attr("src", imgs[0]);
imgs.reverse()
}, function() {
$(this).attr("src", "http://lorempixel.com/100/100/nature");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="element" width="100px" src="http://lorempixel.com/100/100/nature" />
What about some simplicity?
var counter = 1;
$("#element").hover(function () {
counter = (counter===3) ? 1 : (counter+1);
$(this).attr("src", 'img'+counter+'.png');
}
Not sure if this will work just something I looked up but you can try it.
Just add more variables to it.
jQuery(document).ready(function($) {
//rollover swap images with rel
var img_src = "";
var new_src = "";
$(".rollover").hover(function(){
//mouseover
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
},
function(){
//mouse out
$(this).attr('src', img_src); //swap images
$(this).attr('rel', new_src); //swap images
});
How about this?
$(document).ready(function(){
var count = 1;
$("#element").hover(function() {
count++;
$(this).attr("src","img"+count+".png");
if(count == 3){
//Reset the count
count = 0;
}
}, function() {
$(this).attr("src", "img1.png");
});
});
I am building a image carousel with fade in/out animation with javascript and jquery.
Before the next images fades in, the current image shows up briefly although it's faded out. This happens even though I use onload to make sure the next image is loaded and sized properly.
(The live code is: www.jbkphotographs.com/nepal.html)
function moveToNextImg(){
if(current === imgArray.length-1){
current = 0;
}
else{
current++;
}
updateIndex();
//#imgWrapper is <div> that contains <img>
$("#imgWrapper").fadeOut("slow",loadImg);
}
function loadImg(){
imgName = imgArray[current].getAttribute("src");
nextImg.src = imgName.replace("_Thumb","");
nextImg.id = "currentImg";
nextImg.onload = function(){
if((nextImg.height) > (nextImg.width)){
nextImg.style.width = "42.5%"
}
else{
nextImg.style.width = '750px';
}
imgWrapper.appendChild(nextImg);
}
$("#imgWrapper").fadeIn("slow");
}
I saw it. You have that effects befause you are fading in the image before it has been loaded.
a) You should preload the images , before sliding to have the fadein
fadeout effect
b) Otherwise put the fade in effect in the onload
callback of the images:
function moveToNextImg(){
if(current === imgArray.length-1){
current = 0;
} else {
current++;
}
updateIndex();
//#imgWrapper is <div> that contains <img>
$("#imgWrapper").fadeOut("slow",loadImg);
}
function loadImg(){
imgName = imgArray[current].getAttribute("src");
nextImg.src = imgName.replace("_Thumb","");
nextImg.id = "currentImg";
//This code will run only when images will be loaded
nextImg.onload = function(){
if((nextImg.height) > (nextImg.width)){
nextImg.style.width = "42.5%"
}
else{
nextImg.style.width = '750px';
}
imgWrapper.appendChild(nextImg);
$("#imgWrapper").fadeIn("slow");
}
//any code here will run immediately before the onload runs
}
I have built a gallery viewer with a preload function.
The preload function is as follows:
$.preloadFullImages = function() {
// Create array of images
var set = [];
$('.slide-item img').each(function() {
var img = $(this).data('src');
var id = $(this).parent().attr('id');
$(this).remove();
set.push([img,id]);
});
// Set current image
var current = 0;
var iterate = function() {
var current_src = set[current][0];
var current_id = set[current][1];
var temp = '<img src="'+current_src+'" />';
var target = '#'+current_id;
var targetImg = '#'+current_id+' img';
// Load 'temp' image
$(temp).bind('load', function() {
// Show image
$(target).append(temp);
$(targetImg).show();
$(this).remove();
});
if ( ++current < set.length ) iterate();
};
iterate();
};
On load of the page, images are loaded sequentially.
The problem is until all the images are loaded, the animation between images (prev and next arrows) is stunted and doesn't work correctly. I want the gallery viewer to transition smoothly between slides (images) even if not all images are loaded.
You can see a live demo here: http://www.davidclapp.net/portfolio
The issue is especially apparent on the iPhone (safari).
Is there a way to ensure the animation is smooth even whilst images are still loading?
Edit: I am using this plugin for CSS3 transitions - http://ricostacruz.com/jquery.transit/
$.preloadFullImages = function(callback) {
...
if ( ++current < set.length ) iterate();
else if(callback) callback(); //check if callback exists, then call it.
};
iterate();
};
These two lines being the important part.
$.preloadFullImages = function(callback) {
if ( ++current < set.length ) iterate();
else callback();
make a function to call the beginning of your animation, pass it to "preloadFullImages"
I wonder if anyone can help or point me in the right direction.
I have a grid of images. What I'm hoping to do is grab all the images on the page and put them in an array(done). Then every 3 seconds I want to to randomly choose an image, fade it out and fade in another image from the same page.
can someone help me with this?
I've got a nice script I made once, it does use jquery though:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var curIndex = 0;
var src = ['imgs/derp.jpg', 'imgs/derp2.png'];
var fadeTimeInMilliseconds = 2000;
var waitTimeInMilliseconds = 5000;
$(document).ready(function(){
switchImageAndWait(true);
});
function switchImageAndWait(fadeOut2){
if(fadeOut2){
setTimeout(fadeOut, waitTimeInMilliseconds);
}else{
var index = Math.floor((Math.random()*src.length))
if(curIndex == index){
index++;
if(index >= src.length){
index-=2;
}
}
curIndex = index;
$("#swekker").attr("src", src[index]);
fadeIn();
}
}
function fadeOut(){
$("#swekker").fadeTo( fadeTimeInMilliseconds, 0 , function() { switchImageAndWait(false); });
}
function fadeIn(){
$("#swekker").fadeTo( fadeTimeInMilliseconds, 1 , function() { switchImageAndWait(true); });
}
</script>
It's a jquery script script that continuously fades in, waits and fades out again.
To use this script simply add it to an image:
<img width="602" height="400" src="imgs/derp.jpg" id="swekker"/>
How can i know if all loaded in div using jQuery
i want to do this after load all img in #slider div
var imgHeight = $("#slider img").height();
alert(imgHeight);
You can use the load event
$('#slider img').load(function(){
var imgHeight = $(this).height();
alert(imgHeight);
});
if there are more than one image, and you only want to obtain the height after they have all loaded, try this code
var img = $('#slider img');
var length = img.length;
img.load(function(){
length--;
if(length === 0){
alert("All images loaded");
};
});
Well, I've tested the code, and it appears that the problem hasn't got anything to do with the code. When loading the page with the images already in the cache, this is what I get:
Strangely, this does not occur when I force the browser not to use the cache.
Try this:
Attach an onload event listener to each image in the slider.
In the listener:
Give the current image a custom attribute to mark it is 'ready'.
Check if all images are ready. If so, do your thing (i.e. alert(imageHeight))
untested:
(function(){
var slider=document.getElementById('slider'),
images=slider.getElementsByTagName('img'), image, i=-1;
while (image=images[i]) {
image.onload=function(){
this['data-ready']=true;
var image, i=-1;
while (image=images[i]) if (!image['data-ready']) return;
// all images are ready; do your thing here
// ...
}
}
}());