nvcode
nvcode

Reputation: 343

Why won't the variable pass into jQuery.each?

My code:

$('.colorPick').click(function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var canvas2 = this.getContext('2d');
var data = canvas2.getImageData(x, y, 1, 1).data;
var rgb = 'rgb(' + data[0] + ',' + data[1] + ',' + data[2] + ')';
$('.colorPicker').each(function(rgb) {
    var x = this.width;
    var y = this.height;
    var canvas1 = this.getContext('2d');
    gradient1 = canvas1.createLinearGradient(0, 0, x, y);
    gradient1.addColorStop(0, 'rgb(255, 255, 255)');
    gradient1.addColorStop(0.5, rgb);
    gradient1.addColorStop(1, 'rgb(0, 0, 0)');
    canvas1.fillStyle = gradient1;
    canvas1.fillRect(0, 0, x, y);
});
}).disableSelection();

The variable rgb will not pass to the next .each function?

I am new to this if the answer is simple

Upvotes: 1

Views: 5384

Answers (1)

icktoofay
icktoofay

Reputation: 129149

You're defining rgb as an argument to the anonymous function, hiding the parent scope's rgb. If you don't declare it as an argument, it will find the rgb from the parent scope (which is what I think you want):

// ...
var rgb = 'rgb(' + data[0] + ',' + data[1] + ',' + data[2] + ')';
$('.colorPicker').each(function() {
    // ...

Upvotes: 7

Related Questions