Design Background color changer using HTML CSS and JavaScript (original) (raw)

Last Updated : 25 Jul, 2024

Background color changer is a project which enables to change the background color of web pages with ease. There are color boxes on a web page when the user clicks on any one of them, then the resultant color will appear in the background of the web page. It makes web pages look attractive.

**File structure:

--index.html
--style.css
--script.js

**Prerequisites: Basic knowledge of HTML, CSS, and JavaScript is needed. The project contains HTML, CSS, and JavaScript files. The HTML file adds structure, followed by styling using CSS and JavaScript adds functionality to it.

Here is the preview image of the background changer we are going to make.

Background changer preview image

**Approach:

**HTML File: **index.htmlHTML layout is created using the div tag, id attribute, and anchor tags for function calls. It defines the structure of the web page.

**CSS File: **style.css By using CSS properties, we will decorate the web page and make it look attractive. color, width, height, and position properties are given as per the requirement of the project.

**JavaScript File: script.js JavaScript code is used to give functionality to web pages. Here we used the arrow function with the "id" parameter.

HTML `

<title>Background changer using JavaScript</title>
<link rel="stylesheet" href="style.css">

Background Changer

<script src="script.js"></script>

CSS

body { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background-color: #f5f5f5; font-family: Arial, sans-serif; }

h1 { color: #6203e0; margin-bottom: 2rem; }

#colorbox { width: 30%; display: flex; align-items: center; justify-content: space-around; padding: 1rem; background-color: #fff; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); border-radius: 4px; }

#colorbox span { display: inline-block; width: 30px; height: 30px; border-radius: 50%; cursor: pointer; }

JavaScript

function bgchange(color) { let colorarray = ["#e58e26", "#f9b4ab", "#B1FB17", "#78e08f", "#fd79a8"]; document.body.style.background = colorarray[color]; }

var colorarray = ["#e58e26", "#f9b4ab", "#B1FB17", "#78e08f", "#fd79a8"]; var colorbox = document.getElementById("colorbox");

colorarray.forEach(function (color, index) { let span = document.createElement("span"); span.style.backgroundColor = color; span.addEventListener("click", function () { bgchange(index); }); colorbox.appendChild(span); });

`

**Output: In the below-given GIF you can see that whenever the user clicks on the color the background color is changing according to that.