Change Color of Div onclick - Code With Bishal



Learn how to Change Color of div onclick with the help of HTML5, CSS and JS.

This Example is Made With HTML, CSS and JS By Code With Bishal . Just Copy The Code From Here And Paste It Into Your Website. To Preview it scroll the page. If you are having any problem viewing the code just refresh the page or contact us. Change Color of Div onclick is a lightweight and easy-to-use HTML, CSS AND JS code that chnages color of Div for you. In this blog [Change Color of Div onclick], there are five sections on the webpage, in the first section you can get the overview of the blog, in the second section there are few more coding blogs you might like,in the third section you can see the demo of the Change Color of Div onclick made with HTML, CSS and JS, to view the fourth section click on the "View Code" button to reveal the code after that you can copy the code and paste it [that's the fifth section]

You might like this :

SIMPLE BUTTON USING HTML AND CSS
Few days ago
DIV ONLY VISIBLE ON HOVER USING HTML AND CSS
Few days ago
DIV ANIMATION USING HTML AND CSS
Few days ago


Demo :

Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum quae expedita nisi dolor dignissimos at reiciendis quos blanditiis dolore. Nulla architecto iure soluta necessitatibus at sit est maiores commodi fugit.



HTML Code

<!DOCTYPE html>
<html>
<title>Change Color of div on click - Code With Bishal</title>
/*by Code With Bishal - www.codewithbishal.com*/
<body>
<div class="color">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum quae expedita nisi dolor dignissimos at reiciendis quos blanditiis dolore. Nulla architecto iure soluta necessitatibus at sit est maiores commodi fugit.</p>
</div>
<button class="btn btn-primary change">Change Color</button>
</body>
</html>
Copy Contents

CSS Code

.change {
margin-left:auto;
margin-right:auto;
display:block;
margin-top:2%;
margin-bottom:0%;
}

JS(Javascript) Code

const button = document.querySelector('.change')
const body = document.querySelector('.color')
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple', 'orange', 'cyan', 'white']

body.style.backgroundColor = 'violet'
button.addEventListener('click', changeBackground)

function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length)
body.style.backgroundColor = colors[colorIndex]
}