If I have a form and I assign a function to the submit event like so:
$('#miForm').on('submit',hazAlgo);
function hazAlgo(evento) {
console.log('Me han pulsado');
// ...
return false; //evito el submit
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="miForm" action="#">
<button>Púlsame</button>
</form>
I have seen that there are several ways to prevent the submit from happening:
- Let the doSomething function return
false
. - Let the doSomething function call
evento.preventDefault()
. - Let the doSomething function call
evento.stopImmediatePropagation()
.
What are the differences between these three? o When should each be called?
It depends on what you want to do, although the fact that the function
hazAlgo()
returnsfalse
is practically the same as callingevent.preventDefault()
yevent.stopPropagation()
(which you don't mention), it's not the same as callingevent.stopImmediatePropagation()
.Now I'm going to talk about the details:
hazAlgo()
returnsfalse
: will have the following consequences. It will stop the capillarity (orbubbling
) of the event, preventing thoseeventListener
of the elements that contain the person who triggers the event from being triggered. It will stop the default action of the event (in a form, for example, that it is submitted) and will NOT stop the execution of the otherseventListener
that exist for that element.hazAlgo()
callsevent.preventDefault()
: will have the following consequences. It will NOT stop the capillarity of the event, so thoseeventListener
of the elements that contain it will be executed . It will stop the default event action and will NOT stop the execution of the otherseventListener
for this element.hazAlgo()
callsevent.stopImmediatePropagation()
: will have the following consequences. It will stop the capillarity of the event, preventing the capillarity ofeventListeners
the elements that contain the one who triggers the event from firing. It will NOT stop the default action of the event (ie if it is a hook, it will continue with the action of the hook) and will stop the execution of the otherseventListener
.hazAlgo()
callsevent.stopPropagation()
: You don't mention it, but I put it as an extra ball. The following will happen. It will stop the actioncapilaridad
of the event, it will NOT prevent the default action of the event and it will NOT prevent the otherseventListeners
of the element.Having said all this, it could be summarized in the following table: