Reputation: 15
I want to step through an array with a next and previous button. Each button calls the same function as it is in. I have the following code...
function displayPic(i) {
if (i == 0) {
$('#map_holder').empty();
$('#map_holder').append(picArray[i] + '<br><input id="next" type="button" value="Next" onclick="displayPic(' + i + 1 + ');" />');
if (i == picArray.length - 1) {
$('#map_holder').empty();
$('#map_holder').append(picArray[i] + '<br><input id="prev" type="button" value="Prev" onclick="displayPic(' + i - 1 + ');" />');
}
else {
$('#map_holder').empty();
$('#map_holder').append(picArray[i] + '<br><input id="prev" type="button" value="Prev" onclick="displayPic(' + i - 1 + ');" /> <input id="next" type="button" value="Next" onclick="displayPic(' + i + 1 + ');" />');
}
}
}
Any help?
Upvotes: 1
Views: 3171
Reputation: 8291
I do not recommend adding button each time with the new image displayed, it makes it more complicated. How about using a global variable i
and building the form early with <img>
and <button id='prev'>
and <button id='next'>
?
<div id='map_holder'></div>//this will display the image
<button id="prev">Prev</button>
<button id="next">Next</button>
var i = 0;
displayPic(0); //show the first photo initially
$('#prev').click(function(){
i--;
displayPic(i);
});
$('#next').click(function(){
i++;
displayPic(i);
});
function displayPic(i) {
$('#map_holder').empty();
$('#map_holder').append(picArray[i]);
if(i == 0)
$('#prev').hide();
else
$('#prev').show();
if(i == picArray.length-1)
$('#next').hide();
else
$('#next').show();
}
DEMO: https://jsfiddle.net/f4j884cs/1/
Upvotes: 2
Reputation: 4632
Looking at your code, there is an issue. The outer block checks if (i == 0)
then the inner block checks if (i == picArray.length - 1)
. The inner block condition will never evaluate to true
under normal circumstances because the value of i
is guaranteed to be 0
due to the outer if (i == 0)
condition.
Try this to start:
function displayPic(i) {
if (i == 0) {
$('#map_holder').empty();
$('#map_holder').append(picArray[i] + '<br><input id="next" type="button" value="Next" onclick="displayPic(' + i + 1 + ');" />');
}
else if (i == picArray.length - 1) {
$('#map_holder').empty();
$('#map_holder').append(picArray[i] + '<br><input id="prev" type="button" value="Prev" onclick="displayPic(' + i - 1 + ');" />');
}
else {
$('#map_holder').empty();
$('#map_holder').append(picArray[i] + '<br><input id="prev" type="button" value="Prev" onclick="displayPic(' + i - 1 + ');" /> <input id="next" type="button" value="Next" onclick="displayPic(' + i + 1 + ');" />');
}
}
If this still doesn't work, please provide further details.
Upvotes: 0