derp derp - 7 months ago 42
jQuery Question

JQuery: Toggle Push/Splice within Array

That is what i'm trying to do:

I have a list of divs with the same class, everytime I click on one of the divs I would like to store the ID of the respective div in an array, something like:

var array = [];


$("divID").on("click", function(){




What I want to accomplish is that any other click on the same div push/splice the matching ID within the array. A push/splice toggle by ID I guess...

Pushing the div IDs inside an array is not the problem however removing them seems to be a bit more problematic since I'm only capable of clearing the complete array.

How would I have to loop through the array in order to find the matching ID and toggle it on click?



As stated in my OP comment, a simpler approach would be to use a Hash instead of a simple array. Doing this, you can add {ID: 'on'} when clicking, then update the ID and set to 'off' when clicking again. This way, you don't have to remove any items from the array--simply update its status.

For example:

var hash = {};

$("divID").on("click", function(){
  var id = $(this).attr("id");

  // Turns it on
  hash[id] = 'on';               // 'on' or true

  // Alternatively, turn it off
  hash[id] = 'off';              // 'off' or false

  // You can also check its status
  // if (hash[id] == 'on')...