MindOverflow MindOverflow - 6 months ago 18
HTML Question

Jump to next/previous named anchor using left/right arrow keys

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 :)

Answer

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.