3

Using jQuery, I created a pixel art maker in which the user can draw on a grid with a selected color. If I define the selected color value in a variable at the top of the script using let color = $('.color-picker').val();, then try to use that variable in a function lower on the page, for example:

$(".quick-fill").click(function() {
  pixelCanvas.children().find('td').css('background-color', color);
});

only the original color (black) will work. In other words, if you try to select a different color, it won't work. Here's my CodePen if you'd like to view my full code/see how it works.

I got around that before by simply defining the variable inside my function, but I came across someone else who was able to define the variable globally while still allowing for color value change (his CodePen is here). Why won't it work on mine?

nCardot
  • 5,992
  • 6
  • 47
  • 83

1 Answers1

1

Second CodePen link is working because it have that code:

$("#color-picker").change(function() {
    color = $("#color-picker").val();
});

You need update your var color every time it's changed. Otherwise var color will store only first value.

So give an ID to your input color and update var color when a change happens.

HTML:

<h4>pick a color</h4>
<input id='color-picker' type="color" class="color-picker">

JS:

let color = $("#color-picker").val();
$("#color-picker").change(function() {
    color = $("#color-picker").val();
});
Thiago Martins
  • 119
  • 2
  • 9