Skip to main content

JavaScript – Change Background Color to Any Random Colors on Button Click

Submitted by admin on Mon, 06/06/2022 - 21:36

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.

<button type="button" id="color-button" onclick="changeBg()">Change Background Color</button>


const pageBody = document.querySelector("body");
function changeBg() {
  let color = '#'+(Math.random()*0xFFFFFF<<0).toString(16); = color;


Demo – Change Background Color To Any Random Color on click using JavaScript

Hope this article was helpful and interesting.


Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.