blazerix
blazerix

Reputation: 860

Colorpicker not working as expected

So right now, I can dynamically create elements (2 rows of 12 blocks) and when I click on an individual block, I can change the color of it as well.

However, I am having one problem. When I click on a block to have its color changed, the color picker will pop up beside it, no issues at all. When I add a new set of rows and try to color the same block number, it will replace the color of the block from the previous row.

For example, if I color the 12th block in the first row, then add 2 new sets of rows and click on the same block in the second set, it will act as if I'm clicking on the previous set's block. I am using https://bgrins.github.io/spectrum/ as my colorPicker

Here is a link to what I have done so far:

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

var id_num = 1;
var picker = null;
$(function () {
$(document).on('click', ".repeat", function (e) {
    e.preventDefault();
    var $self = $(this);
    var $parent = $self.parent();
    if($self.hasClass("add-bottom")){
      $parent.after($parent.clone(true).attr("id", "repeatable" + id_num));
      id_num = id_num + 1;
      //picker = null;

    } else {
      $parent.before($parent.clone(true).attr("id", "repeatable" + id_num));
      id_num = id_num + 1;
      //picker = null;
    }
});   
});


$(".container").on("click", "a", function(e) {
var self = this;
console.log(this.id)
console.log(this)

    $(self).spectrum({
      color: "#f00",
      change: function(color) {
          $(self).css('background-color',color.toHexString());
      }
  });

e.stopPropagation();
})

Upvotes: 3

Views: 998

Answers (1)

bbodien
bbodien

Reputation: 1082

The problem seems to be that you are cloning elements which already have the colorpicker events bound.

EDIT: I think I've managed to work around the problem by changing your use of jQuery's clone(). If you tell it to clone without including events (omitting the first parameter to clone() which defaults to false, the DOM objects will be created without the colorpicker pointing at the old ones.

Here's an example that I think is doing what you are looking for. I've just removed the true params for clone(). No changes to HTML or CSS.

Upvotes: 1

Related Questions