[JavaScript] button과 이벤트
버튼의 이벤트 속성으로는 무조건 JS가 와야한다.
1. 버튼 만들기
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="button" value="Button!" />
</body>
</html>
<input type="button"> 을 사용하면, button을 만들 수 있다.
value는 button위에 나타날 글자를 설정해줄 수 있다.
2. onclick 이벤트
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="button" value="Button!" onclick="alert('button clicked!')" />
</body>
</html>
onclick 을 사용하면 버튼을 눌렀을 때 일어날 이벤트를 만들어줄 수 있다.
위 코드에서는 버튼을 눌렀을 때, " button clicked! "라는 알림이 뜨도록 했다.
onclick 이외에도 onchange, onselect 등 많은 이벤트들이 있다.
3. 나이트 모드와 라이트 모드 구현
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>나이트 모드와 라이트 모드</h1>
<input
type="button"
value="Night"
onclick="
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';"
/>
<input
type="button"
value="Day"
onclick="
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';"
/>
</body>
</html>
onclick 에 document.querySelector('body')는 'body' 태그 내에 적용할 효과라는 의미이고,
.style.backgroundColor(또는 color)은 style 중 배경색(또는 글자색)에 대한 정보를 주는 부분이다.
아래 사진은 각각 Night 버튼과 Day 버튼을 클릭했을 때 보여지는 화면이다.
4. 토글 버튼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>나이트 모드와 라이트 모드</h1>
<input
id="dark_light"
type="button"
value="dark"
onclick="
if (document.querySelector('#dark_light').value === 'dark'){
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#dark_light').value = 'light';
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#dark_light').value = 'dark';
}"
/>
</body>
</html>
조건문을 통해 dark_light라는 id에 접근하고,
value 값이 dark일 경우, dark 모드로 화면을 전환하는 코드를 실행하고,
value 값이 light일 경우, light 모드로 화면을 전환하는 코드를 실행한다.
이 때, 배경색과 글자색만 바꾸는 게 아니라 버튼의 value도 바꿔주도록 한다.
5. this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>나이트 모드와 라이트 모드</h1>
<input
id="dark_light"
type="button"
value="dark"
onclick="
if (this.value === 'dark'){
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#dark_light').value = 'light';
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#dark_light').value = 'dark';
}"
/>
</body>
</html>
조건문 내의 id를 불러왔던 document.querySelector('#dark_light') 는 onclick이 속해있는 태그 내부를 의미하는 것이다.
즉, this로 쓰게 되면 더욱 간결하게 원하는 뜻을 표현할 수 있다.
같은 기능을 수행하는 버튼이 여러 개가 생길 때 this를 사용하면 중복을 줄여 훨씬 간결하고 보기 좋은 코드를 작성할 수 있다.