Posted on Feb. 10, 2021, 8 p.m. by Bishal ( 10056)
addEventListener()
removeEventListener()
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.
index.html
index.html
<!DOCTYPE html>
<html>
<head>
<title>Change colour of Div using click event - Code With Bishal</title>
</head>
<!-- created by Code With Bishal - www.codewithbishal.com
-->
<body>
</body>
</html>
script.js
<head> </head>
of your HTML document:<script src="script.js"></script>
script.js
file:
const button = document.querySelector('.change')
const container = document.querySelector('.color')
container.style.padding = "50px";
container.style.margin = "20px";
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple', 'orange', 'cyan', 'white']
container.style.backgroundColor = 'violet'
button.addEventListener('click', changeBackground)
function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length)
container.style.backgroundColor = colors[colorIndex]
}
<!DOCTYPE html>
<html>
<head>
<title>Change colour of Div using click event - Code With Bishal</title>
</head>
<!-- created by Code With Bishal - www.codewithbishal.com
-->
<body>
<div class="color">
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.
</div>
<button class="btn btn-primary change">Change Color</button>
</body>
</html>
const button = document.querySelector('.change')
const container = document.querySelector('.color')
container.style.padding = "50px";
container.style.margin = "20px";
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple', 'orange', 'cyan', 'white']
container.style.backgroundColor = 'violet'
button.addEventListener('click', changeBackground)
function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length)
container.style.backgroundColor = colors[colorIndex]
}