+ 3

Is there any good practice or performance corcern regarding use event.preventDefault() ?

3rd Jul 2018, 1:54 AM
Cristopher Pereira Moreira
Cristopher Pereira Moreira - avatar
3 Antworten
+ 3
[edit: done/reposted] Actually, I've got something wrong here. I'm pulling my answer into an edit window to correct and hopefully other will list other cases where preventDefault is useful in the meantime (such as with keypresses, etc).
3rd Jul 2018, 2:08 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
Correction: I was thinking of a related error-cancel strategy; in the event context this was not the right answer for you. preventDefault() is used when it's okay for an event to propagate up the DOM, then--when the browser would act--the action does not happen. Example: link clicks. I can intercept click() at <body>, do something with the click, then allow the event to propagate to "window" object and do something with the same click event there. I do that here, letting it bubble but preventing click from navigating with preventDefault(): https://code.sololearn.com/W32dMUHAsPnL/#html Best practices: A page using AJAX updates might like to use the built-in event system to retrieve data from a server, but without danger of auto-navigating away -- or preventDefault could allow click auditing while signaling that a link is invalid. Performance: At the same place you preventDefault, you may also want to consider stopPropagation(), which should reduce unnecessary click events bubbling up the DOM.
3rd Jul 2018, 3:21 AM
Kirk Schafer
Kirk Schafer - avatar
0
thanks Kirk!
3rd Jul 2018, 2:01 AM
Cristopher Pereira Moreira
Cristopher Pereira Moreira - avatar