I have a comics website which loops through all images in a db and displays them as thumbnails.
The user can click on one of those images to see it in normal size on a viewComic.php template.
I’d like to allow users to press left and right arrows to navigate images.
So, my idea is:
-
pagination.php handles image display on correct pages (by offsetting) by looping through database result array. The user can click on a result (below) to go to that specific image on the viewcomic.php template.
'<br />IMG: <a href="./templates/viewcomic.php?id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '"> -
Now on viewcomic.php, I get and display the image
$imgid = $_GET['id']; $imgpath = $_GET['image']; <center><img src=".<?php echo $imgpath ?>" /></center>
The user can press left and right arrows to navigate through images…
Question 1: Does Javascript allow you to manually set the index position in an array?
Since I want to allow the user to get next and last images, I want them to start from the image they’re currently on (the one they clicked on in pagination.php), not from the beginning of the image array. I pass along the $imgid in the URL, so I was going to set the javascript img array index == $imgid, which would allow the user to continue scrolling through the images from where they left off.
Question 2: How can I keep the current index of an array?
When I want to go a certain direction, it works fine. But if I want to change directions, I have to press the key twice. I found this is because the index is incremented after (imgIndex++) I’ve pressed the key. Meaning, that when it starts to go the opposite way, it first needs to decrement to return the index to the current image, and then press the key again to finally show the next image. I’m not sure how to fix this. Using ++imgIndex is also problematic because it will skip forward an image.
<?php
getImages() {
//DB connection code omitted
$img = array();
while($row = $catResult->fetch_assoc()) {
$img[] = "'../images/all_comics/" . $row['imgname'] . "'";
}
return $img;
?>
var imgArray = [<?php echo implode(',', getImages()) ?>];
$(document).ready(function() {
var img = document.getElementById("theImage");
img.src = imgArray[0];
var imgIndex = 0;
$(document).keydown(function (e)
{
//next image
if (e.which == 39)
{
if (imgIndex == imgArray.length)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex++];
//now the index is ahead by 1, which is bad if you want to press <-- to get the last image because the index is ahead by 1.
}
//last image
if (e.which == 37)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
});
});
Any ideas?
Much appreciated!
Change the order of operations: