Mick Rustenhoven Mick Rustenhoven - 3 months ago 17
jQuery Question

Generating random colors jQuery not adding css

I am trying to create a random color picker, I want div's having class color to be colored fully in the random generated hex color. I tried adding just 1 block (worked) and now I tried to add it to a foreach .color like shown below:

$("#generateColors").click(function () {
$('.color').each(function () {
$.ajax({
url: '/Pastel/PastelRGB',
type: "Get",
success: function (data) {
$(this).css({
"background-color": data.hex
});
//$("#color1p").text(data.hex);
},
error: function (jqXHR, err) {
LogError(err);
}
});
});
});


My HTML looks like this

<div><input type="button" id="generateColors"/></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>
<div class="color" style="width:200px;height:200px;background-color:white;"></div>


The css just doesn't apply to the div..

I am in a learning process of HTML JS and CSS, so any help would be great!

Greets, Mick

Answer

this inside of success is not referencing your element, but referencing success scope

remember element in the variable and then use it instead of this

$("#generateColors").click(function () {
    $('.color').each(function () {
        var element = this

        $.ajax({
            url: '/Pastel/PastelRGB',
            type: "Get",
            success: function (data) {
                $(element).css({
                    "background-color": data.hex
                });
            },
            error: function (jqXHR, err) {
                LogError(err);
            }
        });
    });
});

or just use parameter of each

.each(function (index,element) { ...
Comments