supersize
supersize

Reputation: 14783

index of current clicked element in array

I would like to know, how it is possible to log the index of a current clicked element of an array.

The array:

var cubesmixed = []; 
var cubes;
for(var i = 0; i < 149; i++) {
    cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random()*2000), 0, 0);
    cubesmixed.push(cubes);
}

and the click function:

$(this).click(function() 
{ 
   console.log(index of current clicked element in cubesmixed); 
});

I'm calling all inside a ready() function.

Thanks in advance!

Upvotes: 0

Views: 1797

Answers (3)

geevee
geevee

Reputation: 5461

i'm not sure i understood what you need (array in this context is a javascript object, not a DOM element, so i can't understand how can someone click it).

anyway, check out jQuery .index() method: http://api.jquery.com/index/

usage:

console.log($(this).index())

hope it helps

UPDATE:

view comments for full solution

Upvotes: 3

Frax
Frax

Reputation: 3093

I checked out your code. Each cube you're creating already has an id. I just added this piece of code to yours and it worked.

cubesmixed.forEach(function(cube){
    cube.click(function(){
        console.log("Cube clicked: " + cube.id); 
    });
});

This is the fiddle: http://jsfiddle.net/Fraximus/jYGR9/

Upvotes: 0

Darius
Darius

Reputation: 5269

(Replace #items with your selector...)

$('#items').each(function(index,element){

   $(element).click(function(){
      console.log(index);
   });

})

This will be more efficient than .index() if jQuery does no caching on the call.

.index() -> O(n) * invocationCount

as opposed to the above method which is just O(n) once for initial setup

Upvotes: 0

Related Questions