Anders Kitson
Anders Kitson

Reputation: 1545

Trying to output separate click functions with jquery based on a array

I have this array that is auto generated based on images in a gallery. I need to give them all seperate click events that output variables from another array on click so I can pass them into a string that is attached to the end of a url to submit to pinterest. The part that is slipping me up is the click event,

Here is the code, so far it just alerts last part of the array and does it twice, I want each click to alert seperately the first array for the first click, and the second array position for the second clicked.

THis is the corresponding array console.logged, it is the individual classes for different buttons to click.

[".btnPinIt , 0", ".btnPinIt , 1"]

for (var j = 1; j < clickArray.length; j++){
    console.log(clickArray[j]);

    $(clickArray[j]).click(function() {
      alert(j);
    });

  }

Upvotes: 0

Views: 40

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

One problem is your j is in the same scope for all handlers, so has a value of clickArray.length when the click occurs, but you should not need separate handlers for this. Use data attributes on the elements and pick them up from a single handler.

Another is that you are indexing the array from 1 instead of 0.

You also need an array that has valid selectors as, at the moment, you have an array of invalid jQuery selectors.

e.g. Assuming you have an array of id selectors:

  clickArray = ["#btnPinIt1",
                "#btnPinIt2"]

  // save the index values on the elements
  for (var j = 0; j < clickArray.length; j++){
    $(clickArray[j]).attr('data-val', j+1);
  }

  // Use a startswith selector (in this example) to handle the clicks

  $("[id^=btnPinIt]").click(function() {
      alert($(this).data('val'));
  });

Simpler still would be to use your class and index them in order from 1 to n:

  $('.btnPinIt').each(function(e, i){
      $(this).attr('data-val', i+1);
  }).click(function() {
      alert($(this).data('val'));
  });

This also chains the click and each.

Upvotes: 1

Related Questions