i have simple rotating banner javascript on site i'm developing. works locally, on ie, firefox , safari not on chrome. there wrong code? i'm new javascript problem baffling me. here's relevant code:
<script language="javascript" type="text/javascript"> adimages = new array ("images/amsite18.png","images/amsite19.png","images/amsite09b.png") thisad = 0 imgct = adimages.length function rotate() { if (document.images) { thisad++ if (thisad == imgct) { thisad = 0 } document.adbanner.src=adimages[thisad] settimeout("rotate()", 3 * 1000) } } </script> </head> <body onload="rotate()"> <div id="banner"> <img src="images/banner1.gif" name="adbanner" alt="ad banner" /> </div><!-- end banner --> </body>
it looks reason isn't working in chrome line:
document.adbanner.src=adimages[thisad]
you're referring element name "adbanner" via document.adbanner
, chrome doesn't support that. you'll have use this:
document.getelementsbyname('adbanner')[0].src = adimages[thisad];
some others things improve code quality:
don't use
language
attribute. not necessary.use format
var x = [...];
create new array. there's no reason use constructor format. none @ all. zippo. no 1 possibly comment on answer reason you'd usenew array(...)
instead. no one.use
var
keyword create variables, , semi-colon end statements. although isn't hurting here, if don't usevar
, javascript assumes you're creating/changing global variable, when may not case. (also, semi-colon rules may little convoluted, helps readability.)why checking
document.images
? it's unnecessary. don't refer anywhere else.crockford suggests using
x += 1
instead ofx++
. not big deal, , lot of people disagree, noticed.always use strict equality (===). kind you're using (==) doesn't take account types;
2 == "2"
return true,2 === "2"
not. again, not big deal, , people don't care, bite later on, in different project.never pass strings
settimeout
. browser evals string, , nobody hangs out peopleeval
stuff. don't need pass string, because you're using function doesn't need arguments! use this:settimeout(rotate, 3 * 1000);
try put script tags @ bottom of body. there 2 reasons this. first, performance. when browser gets script, stops everything parse , execute code. if put @ bottom of body instead of head, page @ least appear load faster. second point addressed next:
try avoid using
onload
. it's gauche. reason need because script in head, , has no access dom yet. if script moved bottom of body (which, reason, might not able to; no big deal), wouldn't have messonload
@ all:<body> <div id="banner"> <img ... /> </div> <script> // copy of code same, // , then: rotate(); </script> </body>
for love of god, don't use
name
attribute. forms, cares? when you're manipulating elements javascript, use id. it's obvious you're doing, ,document.getelementbyid('adbanner')
way fasterdocument.getelementsbyname('adbanner')[0]
.
Comments
Post a Comment