0

First time JavaScript coder here.

Trying to solve this so that an image is displayed when the appropriate button for that image is clicked and then the function continues to show the other image in the Array and loops.

For instance if the banner is displaying image 4 and the user clicks on the button for image 2, then the banner should display image 2 and then rotate to show image 3 and continue looping.

Here is the code:

var i = 0;
var baners = new Array();
baners.push('banner1.jpg');
baners.push('banner2.jpg');
baners.push('banner3.jpg');
baners.push('banner4.jpg');
baners.push('banner5.jpg');



function swapImage(){
var img = document.getElementById("banner");
    img.src = baners[i];
    if (i<(baners.length-1)){i++;
    }else{ 
        i=0;
    }

setTimeout('swapImage()', 2000);        

}



function button1 (){
    var img = document.getElementById("banner");
    img.src = baners[0]

}

I am unsure if it is possible to make one global function for the 5 buttons.

Thank you!

MostOner
  • 3
  • 1

1 Answers1

0

I am unsure if it is possible to make one global function for the 5 buttons.

Yes. Use something like this:

function buttonClicked(number) {
    var img = document.getElementById("banner");
    img.src = baners[number]
    i = number; // set current loop position
}

then call buttonClicked(0) from button1, buttonClicked(1) from button2 and so on. If you want to automatically attach the handlers to the button using a for-loop, check out JavaScript closure inside loops – simple practical example.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I just have one more question, the intervals double when this is executed. Any idea why? they all work at 2 sec but with the button press it takes 4 sec to load the next image and then its 2 sec again. – MostOner Feb 05 '14 at 17:07
  • In your `swapImage` loop you're updating `i` only *after* having changed the image - so after a call to `buttonClicked` the next swap will change nothing. I didn't think of that, but actually I guess it's more userfriendly than showing a banner only less than 2s after the user has clicked :-) – Bergi Feb 05 '14 at 17:19
  • hahaha! yea the interval was just as an example. Its good for what I need now thank you again! – MostOner Feb 05 '14 at 17:30