blazerix blazerix - 2 months ago 15
CSS Question

Event handler not working for all elements

I'm trying to find a way to assign event handlers to each box that I create dynamically. At the moment the user can click "Add above" or "Add below" and 2 rows of boxes will appear wherever they clicked.

I'm also trying to make it so that when the user clicks on a specific square, a colorPicker will pop up and that specific square's color can be changed.

For some reason though, the colorpicker only pops up when the user clicks on the first two rows of squares. If more rows are dynamically added below or above the current set, nothing happens when you click on the squares.

Does anyone know why this might be happening?

What I have done/tried so far :

http://codepen.io/anon/pen/bwBRmw

var theParent = document.querySelector(".container");
theParent.addEventListener("click", doSomething, false)
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget && e.target.id !== "") {
var clickedItem = e.target.id;
console.log("Clicked on " + clickedItem);
var led = document.getElementById(clickedItem)

if(!picker){
console.log("new picker initialized")
picker = new Picker(led)
}
else{
console.log("gets inside else case")
picker.settings.parent = led;
}
picker.show();

}
picker.on_done = function(colour) {
$(led).css('background-color',colour.rgba().toString());
picker.hide()
}

//e.stopPropagation();
}

Answer

Try this on line 2:

$(document).on("click", ".container", doSomething);