Making Your Banner Interactive with Javascript

working example

Banner Image
right now...
  • source image
  • clickCounter
  • bannerSelector (i.e. %7)



the code...

HTML


<div id="theBanner">
<img src="http://wikis.la.utexas.edu/sta/[...]picture-18.jpg" alt="Banner Image">
</div><!-- .theBanner -->


Javascript (jQuery)

hide comments


//this is just of list of the images we'll be cycling through
var banners = Array(
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_1.jpg',
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_2.jpg',
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_3.jpg',
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_4.jpg',
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_5.jpg',
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_6.jpg',
'http://laits.utexas.edu/sta/nick/wikistuff/banner/nick_7.jpg'
);
//clickCounter, as the name suggests, tracks the number of clicks
//because we're initializing the counter at 1, the first image in the
//array—the image with no text—will be skipped on the first cycle...you'll see why in a minute

var clickCounter=1;
$('div.picture a').removeAttr('href'); //<--kills the original link
$('div.picture').css('cursor', 'pointer');//makes the cursor more "clicky"
//line below: "each time time the image is clicked..."
$('div.picture').click(function(event) {//"...do this:"
//some notes on bannerSelector
//% is the "mod" operator...x%y returns the remainder resulting in dividing x by y
//example: 5%3 = 2
//banners.length returns the length of the array, or list containing the images we'll be
// cycling through (7 images)
//because clickCounter increments by 1, mod-ing it against the length of array will
//allow us to loop through images.

var bannerSelector= clickCounter%banners.length;
$('div.theBanner img').attr('src', banners[bannerSelector]); //this changes the source URL of the...
//...banner to the bannerSelectorth image in the array

clickCounter+=1;//adds 1 to clickCounter
});