3

I have a group of images with thumb class. In the click event, I want to know which image the user clicked from the thumbs array of images. Basically, I want the index of (this) image in thumbs array.

HTML

<img class="thumb" src="#" />
<img class="thumb" src="#" />
<img class="thumb" src="#" />
<img class="thumb" src="#" />

Javascript

var thumbs = $('.thumb'); 
$('.thumb').click(function(){

      current_thumb = ??;
});
4
  • You should give an data- attribute and get this from the click event, or give a id_index Commented Apr 27, 2015 at 16:19
  • its not an array, so what do you mean by the index? Commented Apr 27, 2015 at 16:20
  • If you were able to give each image an ID you could just identify them using that. then on click function use "var idx = $(this).attr('id')" - though this does add work to the initial code. Commented Apr 27, 2015 at 16:22
  • @Andrew every element has an index number, they don't need to be in an array. Commented Apr 27, 2015 at 16:23

1 Answer 1

3

Use jQuery's index

var thumbs = $('.thumb'); 
$('.thumb').click(function(){
 var current_thumb = thumbs.index(this);
 alert(current_thumb);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="thumb" src="#" />
<img class="thumb" src="#" />
<img class="thumb" src="#" />
<img class="thumb" src="#" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.