4

jQuery documentation states:

"When utilizing both .preventDefault() and .stopPropagation() simultaneously, you can instead return false to achieve both in a more concise manner..."

This is in regard to the example:

// Preventing a default action from occurring and stopping the event bubbling
$( "form" ).on( "submit", function( event ) {

    // Prevent the form's default submission.
    event.preventDefault();

    // Prevent event from bubbling up DOM tree, prohibiting delegation
    event.stopPropagation();

    // Make an AJAX request to submit the form data

});

My question is how does this work, the using of a " return false" in a function to prevent a form or a default action from occurring. Any references to official javascript documentation or jQuery documentation would be invaluable.

Robert
  • 10,126
  • 19
  • 78
  • 130

1 Answers1

4

Look at the jQuery source

if (ret !== undefined) {
    if ((event.result = ret) === false) {
        event.preventDefault();
        event.stopPropagation();
    }
}

if an event handler return false jQuery will call .preventDefault() and .stopPropagation() on the event

Vijin Paulraj
  • 4,469
  • 5
  • 39
  • 54
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531