javascript-change color onclick()
- Published
- Reading time
- 2 min read
- Length
- 319 words
On this page
Javascript Change Color onclick()#
Changing the color of an element on a webpage can be done easily with Javascript. One way to achieve this is by using the onclick() function.
Example: Change Color on Button Click#
Here is an example of changing the background color of a div element with the id "myDiv" when a button is clicked:
function changeColor() {
document.getElementById("myDiv").style.backgroundColor = "blue";
}
In this example, we define a Javascript function called "changeColor" that sets the background color of the element with the id "myDiv" to blue. We then call this function when a button is clicked:
<button onclick="changeColor()">Change Color</button>
<div id="myDiv">This is my div</div>
When the button is clicked, the "changeColor" function is called and the background color of "myDiv" is changed to blue.
Example: Toggle Color on Button Click#
Another way to change the color of an element with onclick() is by toggling between two colors. Here is an example:
var toggle = false;
function toggleColor() {
var myDiv = document.getElementById("myDiv");
if (toggle) {
myDiv.style.backgroundColor = "red";
} else {
myDiv.style.backgroundColor = "blue";
}
toggle = !toggle;
}
In this example, we define a Javascript function called "toggleColor" that toggles the background color of the element with the id "myDiv" between blue and red. We use a variable called "toggle" to keep track of the current color. When the button is clicked, we call the "toggleColor" function:
<button onclick="toggleColor()">Toggle Color</button>
<div id="myDiv">This is my div</div>
When the button is clicked, the "toggleColor" function is called and the background color of "myDiv" is toggled between blue and red.
Conclusion#
Changing the color of an element with onclick() in Javascript is a simple way to add interactivity to your webpages. Whether you want to change the color with a single click or toggle between two colors, onclick() is a versatile function that can help you achieve your desired effect.