So I'm pretty much new to JS, and I'm trying to write something, and I'm having a problem.
It's a color picker. So I have an object that defines the default color, and then when the color is updated, the different css classes need to be updated as well.
So here's what I was trying to do
var colorPicker = {
mainColor: "red",
backgroundColor: this.mainColor + "bkgd",
}
So problem 1 is I keep getting "undefined" returned for "this.mainColor". If I use colorPicker.mainColor, it hasn't been created yet so it throws an error.
Problem two is if I update mainColor from another function, say to make mainColor = "green", then backgroundColor doesn't automatically update.
Any help is appreciated.
Thanks
tfburges
07-07-2011, 05:57 AM
You just need to make backgroundColor a function so that it always gets executed when called:
var colorPicker = {
mainColor: "red",
backgroundColor: function(){return this.mainColor + "bkgd"}
};
<input type="button" value="1) should say redbkgd" onclick="alert(colorPicker.backgroundColor());">
<input type="button" value="2) change to blue" onclick="colorPicker.mainColor = 'blue';">
<input type="button" value="3) should say bluebkgd" onclick="alert(colorPicker.backgroundColor());">
Thanks for the suggestion but I tried that before and it doesn't work. It still thinks that " this.mainColor " is undefined.
Any other ideas?
tfburges
07-07-2011, 06:13 AM
What browser are you using?
I just tested it on 5 different browsers (including Internet Exploder lol) and it worked in every one. You must not have implemented it correctly. Can you post your entire code?
This is what I tested:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script type="text/javascript">
var colorPicker = {
mainColor: "red",
backgroundColor: function(){return this.mainColor + "bkgd"}
};
</script>
<body>
<input type="button" value="1) should say redbkgd" onclick="alert(colorPicker.backgroundColor());">
<input type="button" value="2) change to blue" onclick="colorPicker.mainColor = 'blue';">
<input type="button" value="3) should say bluebkgd" onclick="alert(colorPicker.backgroundColor());">
</body>
</html>
I figured out a different way to get me the same results, and I wiped everything from yesterday. I had it pretty much exactly as you wrote your js and it didn't work, it kept returning undefined.
But now it looks like:
var colorPicker = {
setColors: function(color){
if (!color) {
this.mainColor = "red";
}
else {
this.mainColor = color;
}
this.backgroundColor = this.mainColor + "bkgd";
},
}
there's some other logic in there that I stripped out for the purposes of the example.
tfburges
07-07-2011, 11:02 PM
There's really no reason whatsoever for the code I provided to not have worked for you. If you copy and paste the HTML into a blank file and try it out, you'll see that it works. You must have been leaving out a small but vital component.
Nonetheless, I'm glad you got it working!