Saturday, November 8, 2008

Image Transition with fadein fadeout effect (variable declaration inside window.setinterval())

i was writing javascript for fadein fadeout image transition using jquery. tried working with window.setInterval() function. found a strange difficulty(atleast strange for me), that any variable declared outside the function will not have scope inside window.setInterval() function. hmm. i had to declare a variable (var i=0;) outside and had to use it inside the function. but inside the function it was giving the variable 'undeclared' and i=i+1 was giving NaN (on checking the value of i with alert function).

var imagespth=new Array();
imagespth[0]="images/image1.jpg";
imagespth[1]="images/image2.jpg";
imagespth[2]="images/image3.jpg";
imagespth[3]="images/image4.jpg";
imagespth[4]="images/image4.jpg";
imagespth[5]="images/image5.jpg";
var i=0;
$(document).ready( function() {
imholder=document.getElementById("imageholder");
imholder.innerHTML="< src='" + imagespth[0] + "'>";
//tried it here also
// var i=0;
window.setInterval(function(){
if(i>=5){
i=0;
//alert("resetting i");
}else{
i=i+1;
}
//alert(i);
//this will do but naahhh.... i dont need this
//var v=Math.floor(Math.random()*6);
$(".scalefx").fadeOut(800);
//another timeout is required to match the fadeout time
window.setTimeout(function(){
imholder.innerHTML="< src='" + imagespth[i] + "'>";
},800);
$(".scalefx").fadeIn(800);
},5000);
});

and simple html

image


i tried few workarounds like tried to initialize the variable only once by try-catch block. generated an exception based on i once and catched the exception and there only declared the value of i.

try{
if(i>0){
//nothing here
}else{
throw 'blast';
}
}catch(exception){
//initialize i here.. and hope its value will be retained
var i=0;
}

of no use.. facing same problem..

The magic.. or say strange magic
ok as i was using an array to show the image, i saw that the value of imagespth[i] was coming correct for any value.. hmmm.. i thought why not declare the variable (integer variable i) as array. so i changed the code to

var imagespth=new Array();
imagespth[0]="images/airtel.jpg";
imagespth[1]="images/allahbad.jpg";
imagespth[2]="images/canara.jpg";
imagespth[3]="images/relience.jpg";
imagespth[4]="images/sbi.jpg";
imagespth[5]="images/videocon.jpg";
var intarr=new Array();
intarr[0]=0;
$(document).ready( function() {
var imholder=document.getElementById("imageholder");
imholder.innerHTML="< src='" + imagespth[0] + "'>";

window.setInterval(function(){
if(intarr[0]>=5){
intarr[0]=0;
}else{
intarr[0]=intarr[0]+1;
}
$(".scalefx").fadeOut(800);
window.setTimeout(function(){
imholder.innerHTML="< src='" + imagespth[intarr[0]] + "'>";
},800);
$(".scalefx").fadeIn(800);
},5000);
});

woooohoooo it works like a charm...