Hi dear welcome to Ascode Blog . In this post we are going to learn How To Change Background Color By Clicking on Button using javascript. First Creat A index.html file Copy This HTML CODE and pest it one your code editor. 2ndly creat style.css file Then Copy The CSS CODE . 3rdly creat ap.js file Then Copy The Javascript CODE and pest it then open the index.html file with your browser.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>background color transition js</title>
</head>
<body style="text-align: center;align-items: center;font-size: 3rem;">
<button id="red">R</button>
<button id="green">G</button>
<button id="blue">B</button>
<button id="yellow">Y</button>
</body>
</html>
CSS
body{
text-align: center;align-items: center;font-size: 3rem;
}
Javascript
let body = document.querySelector('body');
document.querySelector('#red').addEventListener('click', function(){
body.style.backgroundColor = 'red';
});
document.querySelector('#green').addEventListener('click', function(){
body.style.backgroundColor = 'green';
});
document.querySelector('#blue').addEventListener('click', function(){
body.style.backgroundColor = 'blue';
});
document.querySelector('#yellow').addEventListener('click', function(){
body.style.backgroundColor = 'yellow';
});
// document.querySelector('#yellow').onclick = function(){
// body.style.backgroundColor = 'yellow';
// };
0 Comments