LeBlaireau
LeBlaireau

Reputation: 17467

jquery find image in array

hi I have an array of images

["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"]

this is stored as a variable 'allpics' when an image is clicked I want to check for its index within this array.

Any help would be appreciated.

Upvotes: 1

Views: 482

Answers (4)

m7o
m7o

Reputation: 921

var allpics = ["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"];

$('img').click(function(){
    var src = $(this).attr('src');
    var index = $.inArray(src, allpics);
});

Upvotes: 2

Tom Fobear
Tom Fobear

Reputation: 6749

If you do want to use jQuery, I'd imagine you would want to use jQuery.inArray. Alternately, you can use grep. It will find an element in array that satisfies a condition. the index is passed as a parameter in the callback.

http://api.jquery.com/jQuery.grep/

jQuery.grep( array, function(elementOfArray, indexInArray) [, invert] )

so

var img = //clicked elements src attrib

// s is the element selected from the array
var s = $.grep(allImages, function(elem, i) {
    if (img == elem.attr('src'))
    {
        //i is the index in allImages
    }
});

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

jsBin demo

You can use jQuery.inArray() help

var images = ["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"];


$('img').click(function(){
  var src = $(this).attr('src');
  var myArrIndexIs = $.inArray(src, images);
  alert(myArrIndexIs);
});

Upvotes: 0

Sirko
Sirko

Reputation: 74076

You don't need jQuery for that, but can do it with vanilla JavaScript. Use indexOf() (MDN docu):

var index = allpics.indexOf( yourPic );

Upvotes: 2

Related Questions