In this JavaScript tutorial we will create a button that will change the background color of body to any random color on a button click. We will use just plain JavaScript, No JavaScript Library, No JavaScript Framework.
Create a Button
Let’s first create a button with ID color-button that will call a JavaScript function changeBg() on click.
1 | <button type="button" id="color-button" onclick="changeBg()">Change Background Color</button> |
JavaScript
1 2 3 4 5 | const pageBody = document.querySelector("body"); function changeBg() { let color = '#'+(Math.random()*0xFFFFFF<<0).toString(16); pageBody.style.background = color; } |
Demo
Demo – Change Background Color To Any Random Color on click using JavaScript
Hope this article was helpful and interesting.