tags:

views:

15

answers:

1

I've got some code like so:

<div id="thumbs">
    <img src="/media/img/banana.png" />
    <img src="/media/img/apple.png" />
    <img src="/media/img/lobster.png" />
    <img src="/media/img/charismatic_duck.png" />               
</div>

What I'd like is to work out what the following code needs so that it logs 1 if I click the first image, 2 if I click the next etc.

$("#thumbs img").click(function(){
    console.log(_____WHAT GOES HERE?_____)
});

I'm aware that I could add IDs (image1, image2 etc) and use that to work it out, but I'd like a cleaner way if there is one.

+5  A: 
console.log( $(this).index() + 1 )

The .index() method returns a zero-based index number of the img that was clicked (in relation to its siblings).

I added + 1 to give you the 1-based index that you wanted.

There are various other ways of calling .index(). With no arguments, it behaves as I described above.

patrick dw
Ah, index, not indice! Thanks!
Rich Bradshaw
@Rich - You're welcome. :o)
patrick dw