I know this question has been asked before a lot but I checked most of those and didn't find solution to my problem so I'm asking here again.
So, question is:
I'm working on a cinema website project. I added a few pictures as slide show in my home page but for some reason, slideshow is not working properly. It has some glitch in it like sometimes order is not correct and sometimes all pictures try to come up at one time or they change super fast etc.
I guessed maybe it's bcz somehow when I reload the website, the previous onlaod also keeps on working so it's like there are 2 slideshows going on or something like that, so from other solutions I guess I have to put onload=null somewhere maybe but I can't figure it out exactly.
Any help would be really appreciated.
This is my html code for slideshow:
<div class="bg-movies" style="top: 65%;">
<img src='images/slideshow/war.jpg' width='1000' height='300'
onload="setSlide();"/>
</div>
And this is my javascript code:
<script language='javascript'>
<!--
var toprated=new Array('sarkar.jpg','hajwala.jpg','96.jpg','war.jpg');
var pos=0,x;
document.images[1].src='images/slideshow/'+toprated[0];
function setSlide(){
x=setInterval('chgPic()',2000);
}
function chgPic(){
pos=(++pos)%toprated.length;
document.images[1].src="images/slideshow/"+toprated[pos];
}
-->
</script>
Your problem is recursion. You are calling the setSlide()
method once your image is loaded. This will set up the interval to call the chgPic()
, but when the chgPic()
method is called and it updates the image src, the onload
event on the img
tag will be executed again (because an image has been loaded). Therefore setSlide()
will be called again which will set up another interval to call the chgPic()
method. And on and on etc. I'm surprised your browser hasn't crashed.
What you should do is set up the interval (i.e. call the setSlide()
method) once the page has loaded, or even better yet, use jQuery's document ready if you're using jQuery:
$( document ).ready(function()
{
}
And call your setSlide()
method in here.
Although, I wouldn't recommend doing it the way you are. You can use some simple jQuery and CSS to get this to work. Take a look at this link.