In this tutorial we will see how to Change Background Color OnClick using Input Field with JavaScript. getElementById() method, getElementsByTagName() method, value property and style property is used for this purpose.
Table of Contents
HTML Code
HTML code is given below, in this code we have an input field and a button tag with onclick event, this event will trigger a JavaScript function.
<input type="text" id="color" placeholder="#FFFFFF">
<br><br>
<button onclick="changeColor()">Change Color</button>
JavaScript Code
JavaScript Code is given below, in this code getElementById() method is used along with .value property to get the value of the input field.
Then getElementsByTagName() method is used to select the body tag and .style property and .backgroundColor property is used to change the background color of the body of HTML page.
<script>
function changeColor()
{
var color = document.getElementById('color').value;
var body = document.getElementsByTagName('body')[0];
body.style.backgroundColor=color;
}
</script>
Demo
Video Tutorial
Watch our video tutorial on Change Background Color OnClick using Input Field with JavaScript.