How to run javascript image slideshow via external js file? -
i have slider on website ans working fine ... , image changer changes images on slide show , code written in main.html file this
<img src="images/1.jpg" name="slide" width="100%" height="368" /> <script> <!-- var image1=new image() image1.src="images/1.jpg" var image2=new image() image2.src="images/4.jpg" var image3=new image() image3.src="images/3.jpg" //variable increment through images var step=1 function slideit(){ //if browser not support image object, exit. if (!document.images) return document.images.slide.src=eval("image"+step+".src") if (step<3) step++ else step=1 //call function "slideit()" every 2.5 seconds settimeout("slideit()",2500) } slideit() //--> </script>
now working absolutely fine.. want have file name page1.js want put javascript code in file instead of main.html file.. please tell me how put javascript code in page1.js file , call image slide show work fine working having javascript code in same file..
put javascript above file named my-slides.js
, , replace script tag in current html file one:
<script type="text/javascript" src="my-slides.js"></script>
ensure my-slides.js
in same folder html file, otherwise change path accordingly.
fwiw, although have not asked in question, think should mention following:
- consider using curly braces define code blocks in
if
,else
blocks, when single line. improves code readability - this line:
document.images.slide.src=eval("image"+step+".src")
useseval
, should avoid it. not sure accomplished here wrapping string concatenation eval. storeimage
s in array , access index instead. - rather have
settimeout
within function recur, consider usingsetinterval
outside of function.
as requested.
this my-slides.js
should contain.
var numimages = 3; var images = []; (var = 0; < numimages; ++i) { var image = new image(); image.src = 'images/' + (i + 1) + '.jpg'; images.push(image); } var step = 0; function slideit() { if (! document.images) { return; } document.images.slide.src = images[step].src; step = (step + 1) % numimages; } setinterval(slideit, 2500);
Comments
Post a Comment