I have an array of “associative arrays,” i.e. objects, that hold the data of various HTML elements and one other parameter like so:
container[0] = { picker_canvas: document.getElementById("background_picker"),
color_canvas: document.getElementById("background_color"),
hex_text: document.getElementById("background_text"),
mouse_down: false };
container[1] = { picker_canvas: document.getElementById("textbox_picker"),
color_canvas: document.getElementById("textbox_color"),
hex_text: document.getElementById("textbox_text"),
mouse_down: false };
container[2] = { picker_canvas: document.getElementById("font_picker"),
color_canvas: document.getElementById("font_color"),
hex_text: document.getElementById("font_text"),
mouse_down: false };
Each container has a reference to a color picker canvas, a color preview canvas, a textbox that displays the hexadecimal color value, and a mouse_down boolean. Later on I initialize a few event listeners by iterating through the containers like this:
for (i=0; i<3; i++) {
container[i].picker_canvas.addEventListener("mousedown", function() {
container[i].mouse_down = true;
}, false);
container[i].picker_canvas.addEventListener("mouseup", function() {
container[i].mouse_down = false;
}, false);
container[i].picker_canvas.addEventListener("mousemove", function(evt) {
getColor(container[i], evt);
}, false);
container[i].hex_text.addEventListener("change", function(evt) {
drawColorSquare(container[i], evt.target.value)
}, false);
}
but that doesn’t work because i becomes undefined, so I am now trying to get the correct index by doing something like this, but I am not sure how to actually implement it in Javascript
container[i].picker_canvas.addEventListener("mousedown", function(evt) {
container[container.indexof(evt.target)].mouse_down = false;
}, false);
basically I need to search the array of associative arrays for the evt.target and have it return the index of the array. So is this even possible with any built in Javascript functions or will I just have to make my own?
Since it seems you don’t have to worry about Internet Explorer 8 and earlier, use
forEach: