blazerix blazerix - 2 months ago 9
CSS Question

How to assign event handlers to multiple elements (colorPicker)

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 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.

However, my program is a bit buggy, it only works for the first square that the user clicks on and the colorPicker never pops up again.

Does anyone know how I can go about fixing this or if there is a better alternative?

My code:

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

var theParent = document.querySelector(".container");
theParent.addEventListener("click", doSomething, false)

//var picker = new Picker()
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
var picker = new Picker(k)
picker.show();

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

//e.stopPropagation();
}

Answer

I noticed in your CodePen that you didn't post the full code for doSomething. You have a problem because the picker variable is local to the function. If the code execution doesn't land inside the IF-statement, the picker variable is never created. Simply uncomment the code declaring the picker variable outside the function, and remove the var directive from in front of the line of code where you instantiate a new picker. Furthermore, you need to reset the "parent" element of the picker, since there is only one picker on the page: picker.settings.parent = k;

var picker = null; // Initialize global variable

function doSomething(e) {
    console.log("gets inside doSomething")
    console.log(e.target)
    console.log(e.currentTarget)
    if (e.target !== e.currentTarget) {
        var clickedItem = e.target.id;
        console.log("Hello " + clickedItem);
        var k = document.getElementById(clickedItem)

        // Reference the global "picker" variable
        if (!picker) {
          picker = new Picker(k)
        } else {
          // Set the "parent" element of the picker to the newly clicked element
          picker.settings.parent = k;
        }
        picker.show();

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

    //e.stopPropagation();
}
Comments