If you have started coding in Javascript, you may want to change text color(font color) or button color on a button click using Javascript, to do some dynamic changes on the HTML document, so in this article, I have mentioned how we can change text color using Javascript.
We will change color of an HTML element using HTMLelement.style.body.color = 'some color';
this javascript code.
We can also change the specific style, such as element color, background color, size, etc.
Change Text Color on Button Click using Javascript
In this example, we will change <div> text color on clicking button.
<html>
<head>
<style>
button {
height: 30px;
width: 100px;
}
</style>
</head>
<body>
<div id = "fonts"> Click the button to change the color of font in this paragraph.</div>
<button onclick = "changeTextFontColor()" id = "btn" >change color</button>
<script>
// function to change the font color of text
function changeTextFontColor() {
let button = document.getElementById("fonts"); // access the paragraph by id
let color = button.style.color;
if (color == "red") { // if paragraph text color is red change it green otherwise change it to red.
button.style.color = 'green';
} else {
button.style.color = 'red';
}
}
</script>
</body>
</html>
Fiddle: https://jsfiddle.net/6soeL2kw/
In the above Javascript code, we are picking element by using .getElementById()
and then using element.style.color to change color.
If Color = green then we change it to red or else vice-versa.
Change the Button Color on Click using Javascript
In the above example, we change text color, but in this example, we will change color of clicked button
<html>
<head>
<style>
button {
height: 30px;
width: 200px;
}
</style>
</head>
<body>
<div id = "fonts"> Click the button to change the color of font of button</div>
<button onclick = "changeButtonColor()" id = "btn" >change button color</button>
<script>
// function to change the font color of text
function changeButtonColor() {
let button = document.getElementById("btn"); // access the button by id
let color = button.style.color;
if (color == "red") { // if button color is red change it green otherwise change it to red.
button.style.color = 'green';
} else {
button.style.color = 'red';
}
}
</script>
</body>
</html>
https://jsfiddle.net/uqn0oedk/
We are doing same procedure in the above example also, instead of picking <div> Id we are taking button element Id and changing it's color using element.style.color.
You may also like to read:
Get enum key by value in Typescript
What is JQuery IsNumeric like function in Javascript?
Password and Confirm password validation using Javascript
Uncaught Error: "Cannot use import statement outside a module"
Convert seconds to hh:mm:ss using Javascript