/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Beginner Javascript user – HELP

The webpage needs to cycle four images, without user input (like an animation or slideshow).

This is my current code:

<!DOCTYPE html>
<html>
<body onload=”setTimeout(firstImage, 3000)”;

<h1> Traffic lights </h1>

<p> Please click the button to change the lights. </p>

<img id=”trafficLight” src=”red.jpg”>

<script>
var light = [“red.jpg” ,”redandamber.jpg” ,”green.jpg” ,”amber.jpg”,];

var index = 0;

function firstImage() {
index = index + 1;
var image = document.getElementById(‘trafficLight’);
image.src=light[index];
}

</script>
</body>
</html>

Any help is greatly appreciated! x

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERJun 07.2016 — To make it automatic, you need to use 'setInterval' instead of 'setTimeout'.

Also, the variable index need to be reset to zero after the increments

to go back to the first image.

Finally, I used 'alt' in the image to show something when the image is not available.

<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body onload="setInterval(changeImage, 3000)";

&lt;h1&gt; Traffic lights &lt;/h1&gt;

&lt;p&gt; Please click the button to change the lights. &lt;/p&gt;

&lt;img id="trafficLight" src="red.jpg" alt="red.jpg"&gt;

&lt;script&gt;
var light = ["red.jpg" ,"redandamber.jpg" ,"green.jpg" ,"amber.jpg",];

var index = 0;

function changeImage() {
index = (index+1) % light.length;
var image = document.getElementById('trafficLight');
image.src=light[index];
image.alt=light[index];
}

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;


Not the way I would have approached the problem, but it gets the job done.

I tried to keep most of your code intact.

I'm not sure I understand the message about clicking the button as there is no button to click. ?
Copy linkTweet thisAlerts:
@Hannah0809authorJun 08.2016 — The 2nd 3rd and 4th images are all undefined. Any suggestions?

Thanks again
Copy linkTweet thisAlerts:
@JMRKERJun 08.2016 — The 2nd 3rd and 4th images are all undefined. Any suggestions?

Thanks again[/QUOTE]


Where are the images located? Same directory or a different one?

Show URL where images are located.
×

Success!

Help @Hannah0809 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...