JQuery load and fade in images when users scroll to the div
<div class="strategy" class="hidden">
<img src="http://pic1.com" />
</div>
<div class="creative" class="hidden">
<img src="http://pic2.com" />
</div>
I have a load of div of images like above. My intention is ONLY when users scroll down to a div, then the image inside that div starts to load with an indicator and after finished loading the image fades in. Currently I used jquery.appear plug in to make the images fade in when user scrolls down to the div. But all the images loaded at once. I want ONLY when user scroll down the div then load then fade in. Please help me on this. Here is the code I used for fade in with plug in.
$(document).ready(function() {
function fadeInDivs(elements){
for(var i=0;i<开发者_StackOverflow社区;elements.length;i++){
array[i].appear(function(){
$(this).css('visibility', 'visible')
.hide()
.fadeIn(3000);
}
}
});
var array = [$('.strategy'),$('.creative')];
fadeInDivs(array);
Perhaps because of my poor explanation, people mistaken my question. I am not asking how to detect whether user scroll down to the div (I already succeed doing that). My question is how to LOAD image using AJAX with indicator when user scrolls down to the div.
There was a small bug in your code:
function fadeInDivs(elements){
for(var i=0;i<elements.length;i++){
elements[i].appear(function(){
$(this).css('visibility', 'visible')
.hide()
.fadeIn(3000);
// The following brace & bracket were missing
});
}
}
var array = [$('.strategy'),$('.creative')];
$(document).ready(function() {
/// IMO it's better to define the function outside of this, then call it inside.
fadeInDivs(array);
});
Example posted here: http://jsfiddle.net/NqWLH/1/
There is an easier way:
$('.strategy, .creative').hide().fadeIn();
Don't put src on the images, use an alternative attribute :
<div class="strategy" class="hidden">
<img srcToLoad="http://pic1.com" />
</div>
<div class="creative" class="hidden">
<img srcToLoad="http://pic2.com" />
</div>
then when scroll reaches your image (assuming it reaches the first one in our example) :
var imgSrc = $('.strategy img').attr('srcToLoad');
$('.strategy img').attr('src', imgSrc);
also, on all the images inside the hidden class a load handler :
$(function() {
$('.hidden img').load(function() {
$(this).parent().fadeIn(3000);
});
});
the load handler will execute when the image finishes loading.
精彩评论