Reputation: 11
I'm trying to change the color of a background using jQuery. I've made an array with color names and their value.
If I do
console.log(colorValue);
I get the classname I want to use to find the corresponding color, when I do
console.log(colorArr.colorValue);
I get an undefined, but when I do
console.log(colorArr.red);
I get the corresponding color:
function colorChange(){
$('div.colorpicker ul li a').on('click', function() {
var colorArr = {'greenyellow': '#d2db46', 'lightgreen': '#8dc13f', 'darkgreen': '#56a174', 'blauw' : '#3199d1', 'darkblue':'#326b9b', 'darkpurple':'#584586' , 'purple':'#985494', 'red':'#ca4538', 'orange' : '#e27a37', 'darkyellow': '#f8c040', 'lightyellow': '#e4de42'};
var changeBackground = $('div.header_blue, div.reactie, section#adres, section#referenties_single div.pager');
var changeColor = $('section#tevredenklanten h1, section#referenties_single h2.klant, section#referenties_single .wat_gedaan h2');
var colorValue = $(this).attr('class');
console.log(colorValue);
//console.log(colorArr);
console.log(colorArr.colorValue);
//console.log(colorArr.red);
changeBackground.animate({backgroundColor:colorArr.colorValue}, 600);
});
}
Does anyone know what I have to do?
Upvotes: 1
Views: 85
Reputation: 7375
Try below code
colorArr[ colorValue ]
We can access the object values by passing the key
colorArr["greenyellow"]= it yields the corresponding result.
Upvotes: 0
Reputation: 74036
Access your object using the bracket notation, when the property name is stored in another variable:
colorArr[ colorValue ]
When using the dot notation JavaScript searches for a property with the very name "colorValue", which is not present, and hence returns undefined
.
Upvotes: 1
Reputation: 388316
Since colorValue
is not the object key but it contains the key to be looked for you need to use []
notation instead of .
notation
console.log(colorArr[colorValue]);
When you say colorArr.colorValue
it looks for a key called colorValue
in the object colorArr
which does not exists thus it returns undefined
Upvotes: 4