views:

39

answers:

1

I am building a photography portfolio for a client and decided to make it a little bit more interactive. I got rid of all buttons on the site and had the user interact with the site using key strokes. My original code used:

$(document).bind('keydown', function( e ) {

but this unfortunately would not allow the user to interact with the pictures that were loaded via jquery. so the visitor could only interact with the first picture. I looked around and found that the .live() method was supposed to bind an event to all objects whether loaded when the document loads, or after the fact. But for some reason it does not work with my code. I am using jquery 1.4.2 and this is a sample piece of my code:

$(document).live('keydown', function( e ) { 

 if (e.keyCode == 32) { 

     var imgwidth = $('#gallery img').attr('width');

     if(imgwidth == 640) {

     $('#content div#image').removeClass('large');

     $('#content img').removeClass('large');

     }else{

     $('#content div#image').addClass('large');

     $('#content img').addClass('large');

     }
     return false;
     };
 });

Any help would be greatly appreciated!

A: 

I don't think the problem is with the way you are binding the events.

Inside your event handler, you do for example:

var imgwidth = $('#gallery img').attr('width');

This will give you the width of the first image (see the attr docs).

How do you determine which image the user is interacting with? If it has focus, then you can do e.g.

$('#gallery img').live("keydown", function(e) {
  // here, 'this' is the DOM image object, and $(this) is the jQuery object for it
  // ...
});

...but the point is, you need some way of letting the computer determine which image the user intends to interact with.

sje397
The imgwidth part only needs to find the first image. I have it in there to determine of the state has been toggled or not so you can press space once to enlarge ass the images in #gallery, and then again to get rid of the class that enlarges them. The #gallery div is replaced with fresh images every time the user presses the arrow keys. I threw an example online: http://werchris.com/emily . I have other key events in the keypress, so would setting the live() to #gallery img solve the problem?
Chris Anderson
@Chris Anderson: you shouldn't have multiple elements with the same ID (e.g. `id="image"`)
sje397