This method stops the event if it is stoppable, meaning that the default action that belongs to the event will not occur. It just prevents the default browser behaviour. Developers use preventDefault() in many cases For example,
- When clicking on a link, prevent the link from following the URL
- When clicking on a checkbox, prevent Toggling a checkbox
- When clicking on a “Submit” button, prevent it from submitting a form
Return false follow three steps
- First It stops the browser’s default behaviour.
- It prevents the event from propagating the DOM
- Stops callback execution and returns immediately when called.
Developers use the return false in many different cases. For example,
- Depending upon the boolean(true or false) value If a form field (fname) is empty, then the function alerts a message, and returns false, to prevent the form from being submitted.
- In order to avoid bubbling (which makes an event propagate from a child element to a parent element)developers have started to use return false statements to stop such propagation.
Note: This behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up. Returning false from a regular DOM event handler does absolutely nothing.
Below are some examples to demonstrate the above:
Example 1: Behaviour without PreventDefault( ) and Return false
Explanation: The link performs its default action as no condition is mentioned to stop it.
Example 2: with PreventDefault()
Explanation: In the output, the default function of the link i.e. connecting to another website has been stopped. Instead, an alert is shown using the preventDefault method.
Example 3: with Return false depending upon boolean (true or false)
Explanation: Since the button is pressed without filling the input field an alert appears because of the condition set in <script> tag which prevents default submit button action and returns false.