Image sequencing function alternates incorrect image
I am new to HTML, JavaScript, CSS and I am taking a web design class. I have to make a banner ad that alternates between two different images ( banner1.jpg
and banner2.jpg
). The problem I am facing is when my site loads, it shows banner1.jpg
above <h2>
and court.jpg
below. Then it changes court.jpg
to banner2.jpg
, then to banner1.jpg
, alternating between the two banners. banner1.jpg
above <h2>
remains static. Here's the relevant code:
<script type="text/javascript">
/* <![CDATA[ */
var curImage="banner1";
function bannerAd() {
if (curImage == "banner2") {
document.images[1].src = "images/banner1.jpg";
curImage = "banner1";
}
else {
document.images[1].src = "images/banner2.jpg";
curImage = "banner2";
}
}
/* ]]> */
</script>
</head>
<body onload="var changeImages=setInterval('bannerAd()', 2000);">
<header>
<h1>Basketball Almanac</h1>
</header>
<section class="main">
<img src="images/banner1.jpg" alt="Banner image" />
<h2>Basketball Analysis</h2>
<p><span class="companyname">Basketball Almanac</span> is your one-stop site for in-depth basketball analysis and statistics.</p>
<img class="main" src="images/court.jpg" alt="NBA Court" />
How can I make it so that only changes banner1.jpg
? Thanks in advance for any help and let me know if it helps to include more code here.
source to share
Simple, javascript arrays are 0-based, so the frist object is [0]
So you want
var curImage="banner1";
function bannerAd() {
if (curImage == "banner2") {
document.images[0].src = "images/banner1.jpg";
curImage = "banner1";
}
else {
document.images[0].src = "images/banner2.jpg";
curImage = "banner2";
}
}
or simplify it a little
var curImage="images/banner2.jpg";
function bannerAd() {
if (curImage == "images/banner1.jpg") {
curImage= "images/banner2.jpg";
}
else {
curImage = "images/banner1.jpg";
}
document.images[0].src = curImage;
}
source to share
var curImage="images/banner2.jpg";
function bannerAd() {
if (curImage == "images/banner1.jpg") {
curImage= "images/banner2.jpg";
}
else {
curImage = "images/banner1.jpg";
}
document.images[0].src = curImage;
}
var curImage="banner1";
function bannerAd(n) {
if (curImage == "banner2") {
document.images[n].src = "images/banner1.jpg";
curImage = "banner1";
}
else {
document.images[n].src = "images/banner2.jpg";
curImage = "banner2";
}
}
//bannerAd(1)
<body onload="var changeImages=setInterval('bannerAd(0)', 2000);">
<header>
<h1>Basketball Almanac</h1>
</header>
<section class="main">
<img src="images/banner1.jpg" alt="Banner image" />
<h2>Basketball Analysis</h2>
<p><span class="companyname">Basketball Almanac</span> is your one-stop site for in-depth basketball analysis and statistics.</p>
<img class="main" src="images/court.jpg" alt="NBA Court" />
source to share