자바스크립트 예제를 하나씩 연습해보려한다.
DOM연습을 위해 랜덤으로 배경색을 바꿀수있는 color-flipper를 만들어보았다.
html
<div class="container">
<div class="contents">
<p>background color : <span>pink</span></p>
<button class="button">click me</button>
</div>
</div>
css
.container {
width: 100%;
height: 100%;
background-color: pink;
display: flex;
justify-content: center;
align-items: center;
}
.contents {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
p {
text-transform: capitalize;
padding: 10px 20px;
border-radius: 10px;
background-color: #000;
color: #fff;
font-weight: bold;
}
span {
color: pink;
}
button {
text-transform: uppercase;
border: 1px solid #333;
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: #fff;
}
js
$(document).ready(function () {
$(function () {
const background = document.querySelector(".container");
const changeText = document.querySelector(".contents span");
const btn = document.querySelector(".button");
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);
});
});