I have posted a sample jQuery slideshow on my blog here:
robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html
In Chrome, it is flickering on each picture. In IE and Firefox it looks fine, and in the standalone version it seems ok too (even on Chrome):
http://robertmarkbram.appspot.com/content/javascript/jQuery/example_slideshow.html
This is the jQuery in question:
<script type="text/javascript">
// ------
// ###### Edit these.
// Assumes you have images in path named 1.jpg, 2.jpg etc.
var imagePath = "images"; // Relative to this HTML file.
var lastImage = 5; // How many images do you have?
var fadeTime = 4000; // Time between image fadeouts.
// ------
// ###### Don't edit beyond this point.
var index = 1;
function slideShow() {
$('#slideShowFront').show();
$('#slideShowBack').show();
$('#slideShowFront').fadeOut("slow")
.attr("src", $("#slideShowBack").attr("src"));
index = (index == lastImage) ? 1 : index + 1;
$("#slideShowBack").attr("src", imagePath + "/" + index + ".jpg")
setTimeout('slideShow()', fadeTime);
}
$(document).ready(function() {
slideShow();
});
</script>
Any assistance would be greatly appreciated!
Rob
🙂
There are 2 possible causes of the flicker.
The first is from the line
$('#slideShowBack').show();.Just remove that line, since it does nothing, since the visibility of
#slideShowBackis never changed.The second is when you
.show()the front image over the back image. Even though the front image is now the same as the back image, it could be causing a momentary flicker.I would approach the problem slightly differently.
I would also enclose all your variables and functions in a self calling anonymous function, so that you don’t clutter the global namespace:
(function() { /* Everything in here */ })();.The most important change in the code is that I don’t suddenly
.show()an image on top of another image, so there’s no possible source of flicker. I also make use of the call back function in.fadeOut(). This is just a function that is called after the fade is done:The HTML:
The Javascript:
jsFiddle
Calling the next slideshow function:
Instead of
index = (index == lastImage) ? 1 : index + 1;you can use the modulus operator%to get the remainder from a division, and instead of using a looping variable you have to set outside theslideShow()function, just pass which photo you want to show in as an argument… Then you can call the next showImage in your setTimeout withslideShow(current+1). Actually,slideShow((index % lastImage) + 1). It’s better to use an anonymous function or a reference withsetTimeoutinstead of an eval.