7

I have the following code

<a class="getty" id="1" href="/...">One<./a>
<a class="getty" id="2" href="/...">Two<./a> 
<a class="getty" id="3" href="/...">Three<./a>

When I'll click on Left or right, I'll need to get the previous ID.
Example : If I'm on id="2", I need to get id="1" if I click on left.

$(document).keydown(function(e){
    if (e.keyCode == 37) {
       $('.getty').attr("id");
       return false;
    } });
    if (e.keyCode == 33) {
       $('.getty').attr("id");
       return false;
    } 
});

How can I do that ?

Thanks

Hussein
  • 40,778
  • 25
  • 110
  • 143
Steffi
  • 6,287
  • 20
  • 68
  • 118
  • Hi! You do have a question! Sorry, just thought it was funny ;-P – Bojangles Mar 22 '11 at 19:33
  • Seriously, with 32 questions you should really know how to format your posts by now. http://stackoverflow.com/editing-help *Edit:* And look at what we've done, guys. – BoltClock Mar 22 '11 at 19:35

3 Answers3

11

To get the previous id when link is clicked.

$('.getty').click(function(e) {
    e.preventDefault();
    var x = $(this).prev().attr('id');
    alert(x);

});

You can do the same for next by using the next() function

Check working example at http://jsfiddle.net/H3hdy/

Hussein
  • 40,778
  • 25
  • 110
  • 143
  • Now, I'm doing : alert($('.getty').next().attr("id");) And it displays null – Steffi Mar 22 '11 at 20:49
  • Use the alert in the click event and make use of $(this) to target current clicked item e.g. alert($(this).next().attr("id")); – Marc Uberstein Mar 22 '11 at 20:57
  • @steffi as Marc said, in your alert use `$(this)` instead of `$('.getty')`. It's also recommended to set a conditional for the last item since doing next() on the last `
  • ` will get you undefined.
  • – Hussein Mar 22 '11 at 21:08
  • I tried `alert($(this).next().attr("id"));` but it's the same – Steffi Mar 22 '11 at 22:39