Jquery selector not working after an element is clicked

I have written a program to generate random colors everytime. and the '+' button is supposed to generate more colors. Clicking on the color will make it the background of the container but every time the '+' button is clicked the click on the color has no effect

Here's the jquery code

var x=$(".container").width();
var l=50-(((25/x)*100)-((10/x)*100));
$(".foot").css({"left":l+"%"});
/*to adjust position*/
$(".foot").click(function(){
fill();
});
var rand,i,z,htm;
$(document).ready(function(){
fill();
/* the following code doesn't work twice after '+' is clicked  */
/*-------------------*/
$(".sel").click(function(){
z=$(this).attr("bg");
$(".container").css({"background-color":"#"+z});
});
/*-------------------*/
});
function fill(){
rand=0;
$(".content").html(" ");
htm="";
for(i=0;i<5;i++){
     while(rand<100000){
rand=Math.floor(Math.random()*1000000);
}
htm+=
"<"+"div class='sel' bg='"+rand+"'"+">"+
"<"+"div class='content-left' bg='"+rand+"'"+">"+
"<"+"div class='colordot' style='background-color: #"+rand+"'"+">"+"<"+"b"+">"+(i+1)+
"<"+"/"+"b"+">"+
"<"+"/div"+">"+
"<"+"/div"+">"+
"<"+"div class='content-right'"+">"+
"#"+rand+
"<"+"/div"+">"+"
 <"+"/div"+">";
 rand=0;
 }
 $(".content").html(htm);
 }

Here's a fiddle on the program https://jsfiddle.net/megatroncoder/2o7xL3p1/

Answers 1

  • In your fill function you recreate .sel elements so they dont have click events any more. They considered to be new. You have to bind event every time you insert new html in container

    var x = $(".container").width();
    var l = 50 - (((25 / x) * 100) - ((10 / x) * 100));
    $(".foot").css({
      "left": l + "%"
    });
    
    $(".foot").click(function() {
      fill();
    });
    
    
    var rand, i, z, htm;
    
    
    
    $(document).ready(function() {
      fill();
    });
    
    function fill() {
      rand = 0;
      $(".content").html("&nbsp;");
      htm = "";
      for (i = 0; i < 5; i++) {
        while (rand < 100000) {
          rand = Math.floor(Math.random() * 1000000);
        }
        htm +=
          "<" + "div class='sel' bg='" + rand + "'" + ">" +
          "<" + "div class='content-left' bg='" + rand + "'" + ">" +
          "<" + "div class='colordot' style='background-color: #" + rand + "'" + ">" + "<" + "b" + ">" +
          (i + 1) +
          "<" + "/" + "b" + ">" +
          "<" + "/div" + ">" +
          "<" + "/div" + ">" +
          "<" + "div class='content-right'" + ">" +
          "#" + rand +
          "<" + "/div" + ">" +
          "<" + "/div" + ">";
        rand = 0;
        z = "";
      }
    
      $(".content").html(htm);
      bindEvents();
    }
    
    function bindEvents() {
      $(".sel").on('click', function() {
        z = $(this).attr("bg");
        $(".container").css({
          "background-color": "#" + z
        });
      });
    }
    

    Here is working fiddle


Related Articles