Here is an example of JavaScript code that changes the background color of an element when a button is clicked:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
#myDiv {
width: 200px;
height: 200px;
margin: 50px auto;
background-color: lightgray;
border: 1px solid #333;
}
</style>
</head>
<body>
<div id="myDiv">This is a div element</div>
<button onclick="changeColor()">Change Color</button>
<script>
function changeColor() {
var colors = ['red', 'blue', 'green', 'orange', 'purple', 'yellow'];
var randomColor = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('myDiv').style.backgroundColor = randomColor;
}
</script>
</body>
</html>
```
In this code snippet, a div element with the id "myDiv" is created. When the button is clicked, the `changeColor` function is called which generates a random color from an array of colors and sets the background color of the div element to the randomly selected color.
Code javascript for color for background
1 answer