1

I made a gallery (using ZenPhoto) and I have all images from one album load in one page. Each image has a named anchor:

<a href="image4_full.jpg" title="image4" name="image4">
  <img src="image4.jpg" alt="image4" />
</a>

---edit--- Note: the anchors are not named in order, the names can be anything, e.g. "carrots", "poodles", "anthrax", "you_always_complicate_things".

I would like to let users jump to the next/previous named anchor using the left/right arrow keys. I will use jQuery if I have to, but I would prefer a shorter solution if that is easily possible. Please help :)

MindOverflow
  • 265
  • 1
  • 2
  • 6

1 Answers1

1

Use the Keydown Event:

var num = 1;
var imagecount = 4;
document.body.addEventListener('keydown', function (e) {
  var keyCode = e.keyCode;
  if(keyCode==37) { //left
    if(num > 1) num -= 1; 
    location.hash = "#image" + num;
  }
  else if(keyCode==39) { //right
    if(num <= imagecount) num += 1; 
    location.hash = "#image" + num;
  }
});

EDIT: To use different names

var num = 0;
var images = new array();
images[0] = "image1";
images[1] = "imageZ";
images[2] = "theend";
var imagecount = images.length - 1;
document.body.addEventListener('keydown', function (e) {
  var keyCode = e.keyCode;
  if(keyCode==37) { //left
    if(num > 0) num -= 1; 
    location.hash = "#" + images[num];
  }
  else if(keyCode==39) { //right
    if(num < imagecount) num += 1; 
    location.hash = "#" + images[num];
  }
});

You could generate the image-array with php (respond if you need the code). The 'good way' would be - as far as I know - to have a json-file with the image names and fetch this from your site, but implementing this without jQuery is a cross-browser adventure.

Community
  • 1
  • 1
Sebb
  • 871
  • 6
  • 16
  • That's very efficient, thank you! However, maybe my code example was misleading, because the anchor names are taken from the image names, so on one page I can have anchors with various names, e.g. "img1234" "carrots" "image4" "fueled by fire" "cabbage". Would it be possible to have the code handle that? – MindOverflow Apr 16 '14 at 16:35
  • Edited the inital response to match your needs ;) – Sebb Apr 16 '14 at 17:26