frequently ask ? : Computers : Programming : Languages : JavaScript : Links

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 8 people (88%) answered Yes
Recently 2 of 3 people (67%) answered Yes

Entry

How can I script an ad rotator?

Feb 3rd, 2001 03:14
Martin Honnen,


A solution that uses the 
  onload
handler of the
  IMG 
element should work with NN3+ and IE4+. The only problem for NN3 and NN4 
is that you need to pass in the link index by hand so that the right 
link is changed when the IMG changes.
<HTML>
<HEAD>
<TITLE>
Ad rotator
</TITLE>
<SCRIPT>
var links = new Array (
  'http://www.faqts.com/index.phtml', 
  'http://JavaScript.FAQTs.com',
  'http://Python.FAQTs.com'
);
var images = new Array (
  'http://www.faqts.com/images/faqts.gif',
  'http://www.faqts.com/images/javascript-faqts.gif',
  'http://www.faqts.com/images/python-faqts.gif'
);
var delay = 5000;
var cur = 0;
var img;
var linkIndex;
function getNextAd (img, linkIndex) {
  cur = ++cur % links.length;
  window.img = img;
  window.linkIndex = linkIndex;
  tid = setTimeout(
   'document.links[linkIndex].href = links[cur]; ' +
   'img.src = images[cur];', delay);
}
var tid;
function createAdRotator (linkIndex) {
  var html = '';
  html += '<A HREF="' + links[cur] + '">';
  html += '<IMG SRC="' + images[cur] + '" BORDER="0"';
  html += ' ONLOAD="getNextAd(this, ' + linkIndex + ')"';
  html += '>';
  html += '<\/A>';
  document.write(html);
}
</SCRIPT>
</HEAD>
<BODY>
<TABLE WIDTH="100%">
<TR>
<TD ALIGN="center" VALIGN="middle">
<SCRIPT>
createAdRotator(0);
</SCRIPT>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>