I am trying to create an image gallery in HTML, CSS. And to use JavaScript to animate the transition. I've managed to get that working, so I decided I wanted a loop within it so that when it reached the last image (4th) it will loop - transition back to the first, and carry on with the sequence until it got to the end again.
Download to look at the site to get an idea of my problem - https://drive.google.com/folderview?id=0B8HDvQ3oZFi6MG5GLTBFWGNmZkU&usp=sharing
I've tried many ways of doing this, I've got it to loop back fine. My entire code:
var imagenum = 0;
var currentimg = 1;
var maxwidth = 0;
$(document).ready(function() {
var Div1 = $("#ip").offset().top;
var Div3 = $("#flash").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() < Div3) {
$("#ip").fadeIn(400);
}
else if($(window).scrollTop() > Div3) {
$("#ip").fadeOut(400);
}});
});
$(document).ready(function() {
$( '.G-li' ).each(function() {
imagenum++;
maxwidth += 830;
});
$( '.G-ul' ).css('width' , maxwidth + 'px');
$( '.rightbtn-inner' ).click(function(){
moveLeft();
});
$( '.leftbtn-inner' ).click(function(){
moveRight();
});
timer();
loop();
});
function moveLeft() {
if( currentimg < imagenum ) {
$( '.G-ul' ).animate( {'marginLeft' : '-=820px' } , 1000 , 'swing' );
currentimg = currentimg + 1;
}
}
function moveRight() {
if( currentimg > 1 ) {
$( '.G-ul' ).animate( {'marginLeft' : '+=820px' } , 1000 , 'swing' );
currentimg = currentimg - 1;
}
}
function timer() {
setInterval(moveLeft, 10000);
}
function loop() {
if( currentimg = imagenum ) {
setInterval(loopbk, 10000);
currentimg = 1; // I did the reset here
}
function loopbk() {
$( '.G-ul' ).animate( {'marginLeft' : '+=2460px' } , 1000 , 'swing' );
/* currentimg = 1; // and tried reset here */
}
}
To make it carry on with the sequence as normal I have to reset the variable currentimg to 1 for this to work. But if i do currenting = 1
in the function loop()
it goes to the last image and carries on for another until looping back.
Or if I place the reset in the function loopbk()
, it loops perfectly until the 2nd image and then proceeds to do the loop resulting in going left too far.
Can someone play around with this and help me as from my eyes this should work, but it doesn't - and I've been trying to solve this for a very long time.
Thank you to anyone that can help.
Andy.