Jun 4, 2024
let element = document.getElementById('someElement');
element.addEventListener('event', functionName);
addEventListener
method is used to set up an event listener.let myDiv = document.getElementById('myDiv');
myDiv.addEventListener('click', doSomething);
function doSomething(event) {
// Event handling code
}
event.type
: Type of event (e.g., click).event.target
: Element that triggered the event.event.currentTarget
: Element to which the event handler is attached.element.addEventListener('click', function(event) {
// handle code
});
element.addEventListener('click', (event) => {
// handle code
});
event.preventDefault()
to prevent the default action.link.addEventListener('click', function(event) {
event.preventDefault();
// handle click
});
document.addEventListener('DOMContentLoaded', function() {
// add event listeners here
});
<!DOCTYPE html>
<html>
<head>
<script src="path/to/script.js"></script>
</head>
<body>
<button id="btn">Click me</button>
<a id="lnk" href="https://google.com">Google</a>
<input type="text" id="txt" />
</body>
</html>
document.addEventListener('DOMContentLoaded', () => {
let btn = document.getElementById('btn');
let lnk = document.getElementById('lnk');
let txt = document.getElementById('txt');
btn.addEventListener('click', (event) => {
console.log(event.type);
console.log(event.target);
});
lnk.addEventListener('click', (event) => {
event.preventDefault();
console.log(event.type);
console.log(event.target);
});
txt.addEventListener('input', (event) => {
console.log(event.target.value);
});
});
addEventListener
, preventing default behaviors, and ensuring element existence before adding listeners.Questions: Leave any questions in the comments.