Search code examples
javascriptjquerydomonmouseover

.on mouseover and eventListener proper placement


I created an etch-a-sketch type of program so that when a user enters a height, width, and select a color choice, they are able to draw on the provided grid below. I am having troubles with the drawing part. I included a link to my code via codepen ... Online 37, I created a mouseover event but I can't figure out why it won't work. Any feedback would be greatly appreciated.

   $("#pixelCanvas td").on("mouseover",  function(){
   var colorPicker = $("#colorPicker").val();
   $( this ).css("background-color",colorPicker );
   });

  https://codepen.io/unicorn1/pen/JpVmZV 

Solution

  • $("#pixelCanvas").on("mouseover", "td", function(){
      var colorPicker = $("#colorPicker").val();
      $(this).css("background-color", colorPicker);
    });
    

    Your td are being dynamically genererated, your #pixelCanvas exists from start, so you want to put an eventListener on the #pixelCanvas, but you only want it to react if a td is actually clicked. Since the #pixelCanvas existed from the start it will know if there happened something inside of it's container, while i generated td wouldn't know that it was supposed to have an eventListener