const parent = document.querySelector('.parent');
const child = document.querySelector('.child');
parent.addEventListener('click', () => {
console.log('Parent clicked during capturing phase');
}, true);
child.addEventListener('click', () => {
console.log('Child clicked during capturing phase');
}, true);
parent.addEventListener('click', () => {
console.log('Parent clicked during bubbling phase');
});
child.addEventListener('click', () => {
console.log('Child clicked during bubbling phase');
});
// 이벤트 캡처링 사용
element.addEventListener('click', () => {
console.log('Capturing phase');
}, { capture: true });
// 이벤트 버블링 중단
element.addEventListener('click', (event) => {
console.log('Stop bubbling');
event.stopPropagation(); // 전파 중단
event.preventDefault(); // 기본 동작 중단
});
const list = document.querySelector('ul');
list.addEventListener('click', (event) => {
if (event.target.tagName === 'LI') {
console.log(`${event.target.textContent} clicked`);
}
});
function handleClick() {
console.log('Button clicked');
}
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
function handleClick() {
console.log('Button clicked');
}
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
button.addEventListener('click', function(event) {
const data = event.target.dataset;
console.log(data);
});
// 디바운싱 함수 예시
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
const handleScroll = debounce(() => {
console.log('Scrolled');
}, 200);
window.addEventListener('scroll', handleScroll);
// 웹 워커 생성
const worker = new Worker('worker.js');
// 메인 스레드에서 웹 워커에게 메시지 전달
worker.postMessage({ message: 'Hello, worker!' });
// 웹 워커에서 메시지 받기
worker.addEventListener('message', (event) => {
console.log(event.data); // "Hello, main thread!"
});
// worker.js
self.addEventListener('message', (event) => {
console.log(event.data); // "Hello, worker!"
self.postMessage({ message: 'Hello, main thread!' });
});
const customEvent = new CustomEvent('myEvent', {
detail: {
message: 'This is a custom event.'
}
});
element.addEventListener('myEvent', (event) => {
console.log(event.detail.message); // "This is a custom event."
});
element.dispatchEvent(customEvent);
<meta name="viewport" content="width=device-width" />
element.addEventListener('touchstart', (event) => {
console.log('Touch event');
event.preventDefault(); // 마우스 이벤트 동시 발생 방지
});
element.addEventListener('mousedown', () => {
console.log('Mouse event');
});