I need 2 simple JavaScript functions that read and change the color of a div on click. I don't want to use frames, jQuery any other means but simple html, css, JS. The code that I have wrote and doesnot work is as follows:
Randomize colours
<script>
var colorArray = {yellow, red, blue, purple};
function readColor () {
color = document.getElementById("color");
}
function changeColor (color) {
var randomColor = colorArray[Math.floor(Math.random() * colorArray.length)];
document.getElementById('color').style.backgroundColor = randomColor;
var colors = document.getElementById('color');
colors.style.backgroundColor = color;
}
</script>
<style type = "text/CSS">
<!--
#color {
background-color: yellow;
}
-->
</style>
<div id="color" style="border-color: #eee; border-style: solid; width: 300px; height: 300px; margin-right: auto; margin-left: auto; margin-top: 200px; padding: 50px; background-color: yellow;" onChange = "readColor ();">
Aici are loc lupta
</div>
<div style="text-align: center; margin-top: 20px;">
<input type="button" name="Change color" value="Change Color" onClick = "changeColor ()">
</div>
I believe just changing
var colorArray = {yellow, red, blue, purple};
to
var colorArray = ['yellow', 'red', 'blue', 'purple'];
should do it..
Demo at http://jsfiddle.net/pYc4P/
I think the problem is that you are not passing in color on the onclick
Should it not read:
<input type="button"
name="Change color"
value="Change Color"
onClick = "changeColor (color)">
You create colorArray
as an object, but you are using it as an array.
Try declaring it as an array instead:
var colorArray = new Array("yellow", "red", "blue", "purple");
Or:
var colorArray = ["yellow", "red", "blue", "purple"];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.