To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
We can change the background color using the backgroundColor property in JavaScript. To use this property, you need to get the element whose background color you want to change, and then you can use the backgroundColor property to set the background color.
The background-color CSS property sets the background color of an element.
Background-color values can be expressed in hexadecimal values such as #FFFFFF, #000000, and #FF0000. Background-color values can be expressed using rgb such as rgb(255,255,255), rgb(0,0,0), and rgb(255,0,0).
In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color
becomes backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.
Your CSS would obviously be something like:
.highlight {
background:#ff00aa;
}
Then in JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';
Or, using a little jQuery:
$('#fieldID').css('background-color', '#FF6600');
Add this script element to your body element:
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>
var element = document.getElementById('element');
element.onclick = function() {
element.classList.add('backGroundColor');
setTimeout(function() {
element.classList.remove('backGroundColor');
}, 2000);
};
.backGroundColor {
background-color: green;
}
<div id="element">Click Me</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With