Reputation: 27
<img src="link" id="hof" </div>
<span id="myspan">Compliment: </span>
<script type="text/javascript">
function change() {
// ---------- Caption and images !! -----------//
var things = ["Slide01", "Slide04", "Slide05", "Slide06"];
var captions = ["Very nice", "Awesome", "Cool", "Best"];
// ^^^^^^^^^^ Captions and Images !! ^^^^^^^^^^ //
var image = document.getElementById('hof');
var thing = things[];
image.src = "link" + thing + ".jpg"; // change the image
span = document.getElementById("myspan");
span.innerText= "Compliment: " + captions[]; //change caption
}
setInterval('change()', 4000);
</script>
So i am new to javascript i am trying to make a slideshow with captions but i need the values in the array to display in sequence like (slide01>slide02>slide03) then repeat from the start when it reaches the last value.
Upvotes: 1
Views: 62
Reputation: 66
<body onload="imgcarousel()">
<img src="" id="hof">
<p id="caption"></p>
<button onclick="imgcarousel()">Next</button>
</body>
<script>
var count = 0;
var things = ['Slide01', 'Slide04', 'Slide05', 'Slide06'] ;
var captions = ['Very Nice','Awesome','Cool','Best'];
function imgcarousel()
{
count++;
var img = document.getElementById("hof");
var caption = document.getElementById("caption");
if(count >= things.length)
{
count = 0;
}
img.src = things[count]+".png";
caption.innerHTML = "Compliments: " +captions[count];
}
</script>
Upvotes: 0
Reputation: 1074238
To answer what you actually asked: You'd use an index
variable defined outside change
. Start with 0
and (after rendering the slide) increment it, wrapping around when you get to things.length
. There's a trick for that last part:
index = (index + 1) % things.length;
Other notes:
Don't use parallel arrays, use an array of objects.
var slides = [
{name: "Slide01", caption: "Very Nice"},
// ...
];
then
var slide = slides[index];
image.src = "link" + slide.name + ".jpg";
span.innerText = "Compliment: " + slide.caption + ".jpg";
Define that array outside change
, there's no need to re-create it every time change
is called.
Don't pass strings into setInterval
or setTimeout
; pass in the function instead:
setInterval(change, 4000);
Consider wrapping all of your code in a scoping function so index
, the array of slides, and the change
function aren't globals:
(function() {
// ...your code here...
})();
Upvotes: 9