버튼을 클릭하여 onclick 이벤트를 작동하고 싶을 때, 활용할 수 있는 코드는 정말 많다.
이번 시간에는 그러한 코드 유형들을 살펴보겠다.
1. HTML 내에서 직접 Onclick 사용
- onclick 속성을 이용하여 인라인으로 이벤트 처리 가능
<button onclick="alert('Button clicked!')">Click Me</button>
> 버튼을 클릭시, alert() 안에 있는 텍스트를 화면에 띄운다.
2. JavaScript 에서 Dom 요소에 직접 onclick 할당
const button = document.querySelector('button');
button.onclick = function () {
console.log('Button clicked!');
};
> 익명 함수임
3. 화살표 함수.
익명 함수 대신, 화살표 함수도 사용 가능
const button = document.querySelector('button');
button.onclick = () => {
console.log('Button clicked with arrow function!');
};
4. 다른 함수 연결
외부에 다른 함수를 정의 후, onclick 으로 연결하기.
const button = document.querySelector('button');
button.onclick = handleClick;
5. 여러 요소에 이벤트 연결.
> 버튼이 여러개인 경우 클래스로 묶여진 버튼들을 querySelectorAll 을 통하여 배열로 부른뒤
const buttons = document.querySelectorAll('.my-buttons');
buttons.forEach(button => {
button.onclick = function () {
console.log(`${this.textContent} clicked!`);
};
});
여기서 foreach란 메서드는 배열(Array)이나 유사 배열 객체(예: NodeList)에서 각 요소를 순회(iterate)하면서 콜백 함수를 실행하는 메서드이다. 원본 배열 변경 가능하며, 반환값이 없으며, 중단 불가능하다는 특징이 있다.
array.foreach(funtion (element, index, array) {
//콜백 함수 내용 })
화살표함수와 사용한다면 위의 코드와 같이
const numbers = [1, 2, 3];
numbers.forEach((num) => console.log(num * 2)); (출력은 2, 4, 6 으로 됨) 이런 식으로 사용 하면 됨.
6. 이벤트 핸들러 제거
onclick을 null로 설정하여 이벤트를 제거할 수 있음.
const button = document.querySelector('button');
button.onclick = function () {
console.log('This will be removed!');
};
// 이벤트 제거
button.onclick = null;
7. 익명 함수와 매개변수 전달
onclick 을 통해 매개변수를 전달할 때는 클로저를 활용.
const button = document.querySelector('button');
button.onclick = function () {
alert(`You clicked on: ${this.textContent}`);
};
8. 익명 즉시 실행 함수 사용
- onclick 내부에서 즉시 실행되는 함수를 사용할 수 있음.
const button = document.querySelector('button');
button.onclick = (function () {
let counter = 0;
return function () {
counter++;
console.log(`Button clicked ${counter} times`);
};
});
+) 추가 활용
1. this를 활용한 컨텍스트 접근
> 중요하진 않은데, onclick 실행시 this로 버튼요소에 접근하여 버튼의 text 부분을 콘솔에 표시해주는 코드임.
const button = document.querySelector('button');
button.onclick = function () {
console.log(`Button text is: ${this.textContent}`);
};
2. 조건에 따른 이벤트 처리도 가능
이런식으로 버튼의 text가 start라고 되어 있다면 starting 이라는 문자가 콘솔에 표시됨.
= > if문도 넣을 수 있다.
const button = document.querySelector('button');
button.onclick = function () {
if (this.textContent === 'Start') {
console.log('Starting...');
} else {
console.log('Stopping...');
}
};
3. HTML 속성으로 매개변수 전달
<button onclick="handleClick('Hello')">Click Me</button>
<script>
function handleClick(message) {
console.log(message);
}
</script>
HTML 에 아예 onclick의 함수에 매개 변수를 전달할 수 있음.
4. 이벤트 객체 활용
const button = document.querySelector('button');
button.onclick = function (event) {
console.log(`Clicked at position: (${event.clientX}, ${event.clientY})`);
};
event 객체로 받아서 버튼 클릭시의 해당 x,y 좌표를 확인할 수 있음.
5. addEventListener 와 비교
onclick의 경우는 한 번에 하나의 이벤트 핸들러만 사용할 수 있다.
그러나, addEventListener 는 여러 이벤트 핸들러를 추가할 수 있다.
// onclick의 경우
const button = document.querySelector('button');
button.onclick = () => console.log('Only this handler will work1');
button.onclick = () => console.log('Only this handler will work2');
두가지의 콘솔을 지정하였으나, 마지막만 출력됨.
// addEventListener의 경우
const button = document.querySelector('button');
// 첫 번째 핸들러
button.addEventListener('click', () => console.log('First handler'));
// 두 번째 핸들러
button.addEventListener('click', () => console.log('Second handler'));
addEventListener 의 경우 두가지의 콘솔이 둘다 출력되는 걸 확인할 수 있음.