Reputation: 5
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
setInterval(function(){
var i = 1;
while(i<3){
var left = $("#"+i).offset().left;
$("#"+i).css({'left':left}).animate({'left':'-10000px'},8000);
if(i == 1){
i++;
}
if(i == 2){
i--;
}
}
},2500);
});
</script>
</head>
<body>
<div id=myDivWrapper style="overflow:hidden">
<div id=1 style="right:0;width:100%;height:100%;background:url('1.jpg');position:absolute;"></div>
<div id=2 style="right:0;width:100%;height:100%;background:url('2.jpg');">
</div>
<body>
</html>
I'm trying to create a JQuery image slider using while loop. here i is the integer i'm incrementing. I don't want the i to be 3 so the loop will stop. Therefor i used a decision statement for finding if i is 1 increment it and if i is 2 decrement it. But this causes lag on browser and it doesn't work. I know this script is crazy. But can you figure out where I made mistake?
Upvotes: 0
Views: 89
Reputation: 5826
Your problem is here..
if(i == 1){
i++;
}
if(i == 2){
i--;
}
See when i is 1, first statement becomes true and then second if will going to be executed so at that time i is 2 so again it decrements value of i. So this is the problem that causes lag on browser. Use else or else if to solve this.
Here it is.
if(i == 1) {
i++;
}
else {
i--;
}
OR
if(i == 1) {
i++;
}
else if(i==2) {
i--;
}
Both are same and will work for you.
Upvotes: 2
Reputation: 7277
Use like below:
if(i == 1){
i++;
}else if(i == 2){
i--;
}
You should use else
Upvotes: 1