In the following javascript code sample:
var myButton = $('#myButton');
myButton.click(function (event) {
/* stuff... */
event.preventDefault();
});
What are de advantages and disvantages of default-preventing the action at the beginning or the end of the function? - supposing the case of unconditionally wanting to prevent it in the end. Is there any technical reason to choose one way?
Surfing the internet i've found only one reference -dead blog, sorry for the Google Cache link-, and points that preventing the default action at the beginning will avoid the action happening in case the js function crashes.
NOTE: i've used jQuery in my example just for familiarity, the question is not about jQuery, the answer for the classical event handling mode will be the same.
I put my preventing code at the beginning for the reason you stated. If there is an error earlier in the js earlier in the function, the default action will already have been prevented. This can be desired behavior in production, but can also help in debugging your development code, consider:
$('a').on('click', function(e) {
console.log('some debugging information here');
// Other stuff
e.preventDefault();
});
If an error were to happen, the page could refresh or follow the href of the anchor before you could read the debugging information. Switching the action to the top will make sure you can read the output in the console.
Edit As Axel points out in the comments, another advantage is you immediately grok that the code is replacing the default action and not supplementing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With