Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Test if an Event Handler is Bound to an Element in jQuery (JavaScript)?
Next article icon

How to prevent the default action of an event in JavaScript ?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The term "default action" usually refers to the default behavior or action that occurs when an event is triggered. Sometimes, it becomes necessary to prevent a default action of an event.

Let's create HTML structure with event and function that needs to prevent the default actions.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <title>Prevent Default</title> </head>  <body>     <a href="https://www.example.com"          onclick="return handleClick()">         Click me     </a>     <script>         function handleClick() {             alert("Event handled");         }     </script> </body>  </html> 

Examples to prevent the default action of an event in JavaScript

1. Using return statement to prevent the default action

In some cases, you can prevent the default action of an event by returning false from the event listener function. This approach only works for certain types of events, such as form submissions and links, and it is generally not recommended as it can cause unexpected behavior in some cases. 

Example: This example uses the "return false" statement to prevent default action.

HTML
<!DOCTYPE html> <html lang="en"> <head>     <title>Prevent Default - Example 1</title> </head> <body>     <a href="https://www.example.com"         onclick="return handleClick()">Click me</a>      <script>         function handleClick() {             alert("Event handled, but default action prevented");             return false; // Prevents the default action         }     </script>  </body> </html> 

Output:

click

Explanation:

  • In the JavaScript code, the handleClick() function is defined to display an alert message and then return false, preventing the default action (navigating to "https://www.example.com").

2. Using stopPropagation() method

The stopPropagation() method can be used to prevent an event from bubbling up to parent elements, which may have their own event listeners that could trigger the default action. Here, we prevent the click event on the child element from bubbling up to the parent element by using the "stopPropagation()" method on the event object.

Example: Here, we are using the "stopPropagation()" method to prevent defaul actions.

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>Prevent Default - Example 2</title> </head> <body>      <a href="https://www.example.com"         onclick="handleClick(event)">Click me</a>      <script>         function handleClick(event) {             alert("Event handled, but default action prevented");             event.stopPropagation(); // Prevents the default action         }     </script>  </body> </html> 

Output:

click

Explanation:

  • In the JavaScript code, the handleClick() function is defined to display an alert message and then call event.stopPropagation(), which prevents the default action (navigating to "https://www.example.com").

3. Using preventDefault() method to prevent the default action

This is the most common approach to prevent the default action of an event. The preventDefault() method is available on the event object that is passed to the event listener function, and it can be used to prevent the default action associated with the event. For example, to prevent a link from navigating to a new page when clicked, you can use the following code:

In general, the preventDefault() method is the recommended approach to prevent the default action of an event in JavaScript, as it is widely supported and provides a clear and consistent way to handle events in a web page or application.

Example: Here, we are using the "preventDefault()" method

HTML
<!DOCTYPE html> <html lang="en"> <head>     <title>Prevent Default - Example 3</title> </head> <body>      <a href="https://www.example.com"         onclick="handleClick(event)">Click me</a>      <script>         function handleClick(event) {             alert("Event handled, but default action prevented");             event.preventDefault(); // Prevents the default action         }     </script>  </body> </html> 

Output:

click

Explanation:

  • In the JavaScript code, the handleClick() function is defined to display an alert message and then call event.preventDefault(), which prevents the default action (navigating to "https://www.example.com").

Next Article
How to Test if an Event Handler is Bound to an Element in jQuery (JavaScript)?
author
snyed
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JavaScript-Events

Similar Reads

  • How to Prevent Default Behavior in an Event Callback in React JS ?
    React JS provides events to create interactive and responsive user interfaces. One characteristic of event handling is to prevent the default behavior of events in certain cases. This article covers the process of preventing default behavior in event callbacks within React JS. Prerequisites:Basic Ja
    3 min read
  • How to Remove Event Handlers in JavaScript ?
    In JavaScript, event handlers are functions attached to HTML elements to respond to specific events like clicks or mouse movements. Removing event handlers effectively detaches the specified function from listening to that particular event on that element. Table of Content Using removeEventListener(
    3 min read
  • How to Disable Ctrl+V (Paste) in JavaScript?
    What is Ctrl + V ?The ctrl+V is a keyboard shortcut used to paste anything from anywhere. It can be disabled for a particular task or page. Let's see how to disable cut, copy, paste, and right-click. To disable the ctrl+V (paste) keyboard shortcut in JavaScript, you would typically capture the keydo
    2 min read
  • How to detect browser or tab closing in JavaScript ?
    Detecting browser or tab closure in JavaScript is essential for preventing data loss or unintended navigation. Using the beforeunload event, developers can prompt users with a confirmation dialog, ensuring they don't accidentally leave a page with unsaved changes or important information. The before
    2 min read
  • How to Test if an Event Handler is Bound to an Element in jQuery (JavaScript)?
    To test if an event handler is bound to an element in jQuery, you can use a few simple methods. These help you check if an event listener is attached to an element, which is useful for debugging. Using .data() to Check Event HandlersYou can use the .data() method to check if any event handlers are a
    2 min read
  • What is JavaScript Strict mode and how can we enable it ?
    JavaScript is a forgiving language as it ignores developers' or programmers' silly mistakes or errors in code like termination of the statement, variable declaration, the wrong data type of variable, hoisting issues, and many more. Sometimes these errors give unusual results which difficult for prog
    5 min read
  • How to Stop Event Propagation with Inline Onclick Attribute in JavaScript?
    The stopPropagation() method in the HTML DOM is used to stop an event from propagating (or "bubbling"). This method is particularly useful when using an inline onclick attribute in JavaScript. HTML DOM stopPropagation() Event Method The stopPropagation() method is used to stop propagation of event c
    2 min read
  • JavaScript Detecting the pressed arrow key
    Sometimes we need to detect the keys and sometimes even detect which keys were pressed. To detect which arrow key is pressed we can use JavaScript onkeydown event. Detecting the pressed arrow key using onkeydown EventThe DOM onkeydown Event in HTML occurs when a key is pressed by the user. Syntax:ob
    2 min read
  • How to Disable Submit Button on Form Submit in JavaScript ?
    Forms are a crucial part of web development as they allow users to submit data to a server. However, sometimes we want to customize the behavior of HTML forms and prevent the default behavior from occurring. This allows you to create a more interactive and user-friendly web application. In this arti
    3 min read
  • How to Disable Ctrl + C in JavaScript ?
    Disabling Ctrl+C in JavaScript involves intercepting the keyboard event and preventing the default action associated with the combination. There are several approaches to disable Ctrl+C in JavaScript which are as follows: Table of Content Using Event ListenersModifying the clipboard eventUsing Event
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences