1

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();
}
blazerix
  • 770
  • 4
  • 8
  • 24
  • 2
    You're using jQuery, wouldn't it be a lot easier to just use jQuery's built in abilty to do event delegation ? – adeneo Sep 21 '16 at 21:27
  • The [documentation for `on`](http://api.jquery.com/on/) has a section about delegated events you might find edifying. – Heretic Monkey Sep 21 '16 at 21:30
  • @adeneo When I do logs to the console, my program does detect being able to click on different squares, so I'm not sure why it isn't working properly. I added the event listener to the parent element, just as jquery would do. – blazerix Sep 21 '16 at 21:30
  • 1
    http://codepen.io/adeneo/pen/PGWwBm – adeneo Sep 21 '16 at 21:41
  • @adeneo Thanks for the response! Do you know why the colorPicker is bound to the element that was clicked on for the very first time? – blazerix Sep 21 '16 at 21:51

2 Answers2

1

Try this on line 2:

$(document).on("click", ".container", doSomething);
Brad Thiessen
  • 553
  • 1
  • 4
  • 13
0

This may not solve all of your problems, but if you remove e.preventDefault();from the click:

 $("body").on('click', ".repeat", function (e) {
        e.preventDefault();

it will let you change colors on each of the newly created sections. Hope it helps?

sean
  • 1,220
  • 9
  • 8
  • Are you sure? I just added a new section below (after removing that line) and no color picker pops up – blazerix Sep 21 '16 at 21:40