Jul 18, 2024
<!-- index.html -->
<button onclick="alert('Hello')">Click Me</button>
// script.js
document.getElementById('button').addEventListener('click', () => {
console.log('Button Clicked');
});
element.addEventListener(event, callback)const button = document.querySelector('#button');
button.addEventListener('click', (e) => {
console.log(e.type); // 'click'
console.log(e.target); // target element
});
button.removeEventListener('click', handlerFunction);
<!-- index.html -->
<button id="modeBtn">Change Mode</button>
// script.js
const modeBtn = document.querySelector('#modeBtn');
let currentMode = 'light';
modeBtn.addEventListener('click', () => {
if (currentMode === 'light') {
document.body.classList.add('dark');
document.body.classList.remove('light');
currentMode = 'dark';
} else {
document.body.classList.add('light');
document.body.classList.remove('dark');
currentMode = 'light';
}
});
/* style.css */
.dark {
background-color: black;
color: white;
}
.light {
background-color: white;
color: black;
}