바닐라 자바스크립트 연습 기록 #1
버튼을 누르면 랜덤으로 배경색이 바뀌는 Color Flipper
• arrays
• document.getElementById()
• document.querySelector()
• addEventListener()
• document.body.style.backgroundColor
• Math.floor()
• Math.random()
• array.length
<title>Color Flipper</title>
</head>
<body>
<div class="container">
<div class="contents">
<p>Background Color : <span>purple</span></p>
<button class="btn">CLICK ME</button>
</div>
</div>
</body>
body {
margin: 0;
}
.container {
width: 100vw;
height: 100vh;
background-color: purple;
display: flex;
justify-content: center;
align-content: center;
}
.contents {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 25px;
}
p {
padding: 30px 90px;
font-size: 30px;
border-radius: 10px;
background-color: #000;
font-weight: bold;
color: white;
}
span {
text-transform: capitalize;
color: purple;
}
button {
padding: 20px 90px;
font-size: 20px;
border: 1px solid black;
border-radius: 10px;
background-color: transparent;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
transition: all 0.3s linear;
cursor: pointer;
}
button:hover,
button:active {
background-color: #333;
color: white;
}
const background = document.querySelector('.container');
const changeText = document.querySelector('.contents span');
const btn = document.querySelector('.btn');
const colors = [
{ id: 1, name: 'red', color: '#ea052d' },
{ id: 2, name: 'orange', color: '#ea7805' },
{ id: 3, name: 'yellow', color: '#eac805' },
{ id: 4, name: 'green', color: '#a1ea05' },
{ id: 5, name: 'skyblue', color: '#05c1ea' },
{ id: 6, name: 'blue', color: '#0545ea' },
{ id: 7, name: 'violet', color: '#7c05ea' },
{ id: 8, name: 'pink', color: '#ffc0cb' },
{ id: 9, name: 'salmon', color: '#fa8072' },
];
const clickHandler = () => {
const randomNumber = Math.floor(Math.random() * colors.length);
background.style.backgroundColor = colors[randomNumber].color;
changeText.textContent = colors[randomNumber].name;
changeText.style.color = colors[randomNumber].color;
};
btn.addEventListener('click', clickHandler);