Reputation: 1005
The images named One.jpg to Ten.jpg are in a folder 'myFolder', which is at my desktop. Below is a code to rotate three images at a time from the total ten in myFolder and the html file is also in the same folder. How to write the src so that this code may work. Alert message gives the name of these 10 images, but further it does not work. Script does not work placed in body tags. What is wrong which is to be corrected for expedted results.
<html>
<body>
<img id = "im1"><img id = "im2"><img id = "im3">
<script type = "text/javascript">
var imgArray = ['One.jpg','Two.jpg','Three.jpg','Four.jpg','Five.jpg', 'Six.jpg', 'Seven.jpg', 'Eight.jpg', 'Nine.jpg', 'Ten.jpg'];
function randOrd(){return (Math.round(Math.random())-0.5)}
imgArray.sort(randOrd);
alert (imgArray); // FOR TESTING
var len = imgArray.length;
var count = 0;
rotate1();
rotate2();
rotate3();
function rotate1() {
document.getElementById("im1").src= imgArray[count];
count++;
if (count>=len) {count = 0}
var tim1 = window.setTimeout("rotate1()", 3000); // 3 seconds
}
function rotate2() {
document.getElementById("im2").src = imgArray[count];
count++;
if (count>=len) {count = 0}
var tim2 = window.setTimeout("rotate2()", 5000); // 5 seconds
}
function rotate3() {
document.getElementById("im3").src = imgArray[count];
count++;
if (count>=len) {count = 0}
var tim3 = window.setTimeout("rotate3()", 7000); // 7 seconds
}
</script>
</body>
</html>
Upvotes: 0
Views: 4281
Reputation: 3106
A best-practice says that the script should be taken out in a separate file and then included at the end of the body like this:
<script src="scripts/YourScript.js"></script>
where src
points to the file.
This is good because:
the browser renders the page as it parses it from top to bottom. This means that when it reaches the script
part at the end of the body
tag, your HTML should be loaded, so the elements used by your scripts will most likely be present.
you can display something to the user until the slowest part (the scripts) load.
you could server the scripts from a CDN so the request-response delay would be minimum.
The only exception to this rule I know of is modernizr
or similar browser and feature detection libraries.
You are missing a semicolon here:
if (count>=len) {count = 0}
it should be like:
if (count>=len) {count = 0; }
Also, when you pass the function to the setTimeout
you can do it like:
window.setTimeout(rotate3, 7000);
Upvotes: 4
Reputation: 44386
Ignoring the "best" practice thing, your problem is that you have no closing </script>
tag.
Upvotes: 1
Reputation: 6214
Ideally, you'd load your script from an external file and there'd be no JavaScript at all in your HTML file. Then you'd serve your documents with CSP headers.
Upvotes: 1