Reputation: 853
so I'm making a simple "gallery" view with jQuery. Simply put, I have an image that starts in the middle on page load, after 5 seconds, that image goes to the left and fades out while a new image goes to the right to replace the previous image while fading in. Once the previous image is done fading out, it gets put back to the stack of images. If the image is not currently being used, I set the opacity to 0 so it's not visible. When it's time for an image to be displayed again, I set the opacity to 1, and of course, fade it in and animate it to the correct spot. I have implemented most of this, and got it to work. But I've run into an issue. Once I fade an image out, it's gone. I don't know if the element is destroyed or if its just completely transparent, but it's gone. I need to re-use this image later, so this is of course an issue. I've seen other websites do what I'm attempting, so it's possible.
Is there a way to fade an element and later on fade it back in for reuse?
jQuery:
$(document).ready(function(){
var images = $('ul.images li');
var lastElem = images.length-1;
var target;
var hasMoved = false;
images.first().addClass('selected');
function slide(target) {
//alert(hasMoved);
for(var i = 0; i < images.length; i++) {
if(target != 0) {
if(i != target && i != target-1) {
$(images[i]).css('opacity', '0');
} else {
$(images[i]).css('opacity', '1');
}
} else {
if(i != target && i != lastElem) {
$(images[i]).css('opacity', '0');
} else {
$(images[i]).css('opacity', '1');
}
}
}
$(images[target]).fadeIn({queue: false, duration: 2000});
$(images[target]).animate({right:'300px'}, 2000);
images.removeClass('selected').eq(target).addClass('selected');
if(target != 0) {
$(images[target--]).fadeOut({queue: false, duration: 2000});
$(images[target--]).animate({left:'300px'}, 2000);
} else {
$(images[lastElem]).fadeOut({queue: false, duration: 2000});
$(images[lastElem]).animate({left:'300px'}, 2000);
}
hasMoved = true;
}
function sliderTiming() {
target = $('ul.images li.selected').index();
target === lastElem ? target = 0 : target = target+1;
slide(target);
};
if(hasMoved === false) {
for(var i = 0; i < images.length; i++) {
if(i === 0) {
$(images[0]).css('opacity', '1');
} else {
$(images[i]).css('opacity', '0');
}
}
}
var timingRun = setInterval(function() { sliderTiming(); },5000);
function resetTiming() {
clearInterval(timingRun);
timingRun = setInterval(function() { sliderTiming(); },5000);
};
});
Upvotes: 0
Views: 189
Reputation: 318192
fadeOut
does not remove the elements, but fadeOut
will set the display
to none
to remove the element from the flow once it's faded out.
If you need to keep the elements in the flow but not visible, you can use fadeTo()
$(images[target--]).fadeTo(2000, 0)
or animate()
, as you're already using it
$(images[target--]).animate({left:'300px', opacity: 0}, 2000);
Upvotes: 1