? jQuery preventDefault() & stopPropagation()
? Quick Overview
In jQuery, preventDefault() and stopPropagation() are used to control event behavior. They help you stop unwanted browser actions and control how events flow through the DOM.
? Key Concepts
- Default Action → Browser’s built-in behavior (link navigation, form submit)
- Event Bubbling → Event moves from child to parent
- preventDefault() → Stops default browser action
- stopPropagation() → Stops event bubbling
? Syntax / Theory
event.preventDefault() stops browser action
event.stopPropagation() stops bubbling
- Both are commonly used inside jQuery event handlers
? Code Example(s)
? View Code Example
$("#myLink").on("click", function(event) {
event.preventDefault();
alert("Link click prevented");
});
? View Code Example
$(".child").on("click", function(event) {
event.stopPropagation();
alert("Child clicked only");
});
? Live Output / Explanation
Expected Behavior
- Clicking the link will not navigate to another page
- Clicking the child element will not trigger parent click events
? Interactive Example
Click the blue button to see stopPropagation, click the link to see preventDefault.
? View Code Example
$("#box").on("click", function() {
alert("Box clicked");
});
$("#button").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
alert("Button clicked only");
});
? Use Cases
- Stopping form submission for validation
- Preventing page reload on button clicks
- Controlling nested click handlers
- Building custom UI interactions
? Tips & Best Practices
- Use preventDefault() when browser behavior is unwanted
- Use stopPropagation() for nested elements
- Do not overuse — it can confuse users
? Try It Yourself
- Create a form and stop submission
- Add nested divs and test bubbling
- Combine both methods in one handler