Browser Default Actions and Custom Events
Preventing Default Actions
Browsers have default actions for many events (like following a link when clicked). You can prevent these with event.preventDefault()
:
let link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault(); // Prevents following the link
alert('Link clicked, but not followed');
});
Creating Custom Events
Custom events in java script is a powerful features that allows developers to create and trigger their own events
You can create your own events:
// Create a custom event
let myEvent = new Event('myCustomEvent');
// Add a listener for the custom event
document.addEventListener('myCustomEvent', function() {
alert('Custom event occurred!');
});
// Dispatch the custom event
document.dispatchEvent(myEvent);
Bubble
Event Bubbling is a term in the DOM where the event an element receives is bubbled (transmitted) to its parent and ancestors, upward in the DOM tree, until it gets to the root.
Example:
<body>
<div id="parent">
Parent Div
<div id="child">Child Div</div>
</div>
<script>
// Event listener on parent
document.getElementById("parent").addEventListener("click", function() {
alert("Parent clicked!");
});
// Event listener on child
document.getElementById("child").addEventListener("click", function(event) {
alert("Child clicked!");
});
</script>
</body>
When you click the "Child Div," you'll see two alerts: "Child clicked!" followed by "Parent clicked!" because the event bubbles up from the child to the parent.
Bubbling behavior can be stopped using event.stopPropagation()
line in the child event handler.