프론트엔드/자바스크립트
랜덤색깔 버튼 만들기
호재이
2023. 2. 13. 16:57
학습한 내용을 복습하기 위해 블로그를 작성합니다.
addEventListener 를 이용하여 버튼을 클릭했을때 배경색과 글자색이 변하게 만들어보겠습니다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Events and This</title>
<style>
button {
width: 100px;
height: 100px;
margin: 20px;
}
</style>
</head>
<body>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<script src="app.js"></script>
</body>
</html>
app.js
// 랜덤색깔을 나타낼수 있게 해주는 함수
const makeRandColor = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
return `rgb(${r}, ${g}, ${b})`;
}
const buttons = document.querySelectorAll('button')
for(let btns of buttons){
btns.addEventListener('click', () =>{
btns.style.backgroundColor = makeRandColor();
btns.style.color = makeRandColor();
})
}
h1 태그도 몇개 생성해서 동일한 작업을 해보자!
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Events and This</title>
<style>
button {
width: 100px;
height: 100px;
margin: 20px;
}
</style>
</head>
<body>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<button>CLICK</button>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<h1>hello world</h1>
<script src="app.js"></script>
</body>
</html>
app.js
const makeRandColor = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
return `rgb(${r}, ${g}, ${b})`;
}
const h1 = document.querySelectorAll('h1')
for(let h1s of h1){
h1s.addEventListener('click', () =>{
h1s.style.backgroundColor = makeRandColor()
h1s.style.color = makeRandColor()
})
}
그런데 버튼과 h1을 작성하다보니 불편한게 있다
btns.style.backgroundColor = makeRandColor();
btns.style.color = makeRandColor();
h1s.style.backgroundColor = makeRandColor()
h1s.style.color = makeRandColor()
버튼코드와 h1 태그가 서로 중복되고 있는걸 볼수있다 이걸 해결해줄수 있는 방법이 있는데 이때 this 키워드가 등장한다
- 이벤트DOM에서 this는 해당 요소를 참조하며 , 실행 컨텍스트나 발동 컨텍스트에 좌우됩니다.
따라서 중복되는 코드를 함수로 따로 빼줍니다.
function colorRize(){
this.style.backgroundColor = makeRandColor()
this.style.color = makeRandColor()
}
그리고 기존 코드를 수정해줍니다.
// btn code
const buttons = document.querySelectorAll('button')
for(let btns of buttons){
btns.addEventListener('click', colorRize)
}
// h1 code
const h1 = document.querySelectorAll('h1')
for(let h1s of h1){
h1s.addEventListener('click', colorRize)
}
중복되었던 코드를 지우고 두번째 인수로 this키워드를 작성했던 함수를 추가하였습니다 여기서 this는 btns, h1s를 참조하며
기존 코드와 동일하게 작동합니다.