loading...

re: What is preventDefault() in JS? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Perhaps you can clarify to me something. If you add an event listener to the click, the event will be passed to your handler function. At this poin...
 

You're talking about event propagation which is a little different than default actions.

preventDefault will stop the browser from taking the default action. For example, pressing Enter in an input field inside a form will submit that form. You can add a keydown listener on the form (or keyup, not 100% sure to be honest) and call preventDefault to prevent the form from being submitted.

Event propagation is simply the event bubbling up the DOM hierarchy. For example, suppose you had a keydown listener on that input field. And you also had a keydown listener on some parent div, for example. By default, that event would propagate up from the input field to the div. If you call stopPropagation() that won't happen.

It's a slight difference but I thought it was worth mentioning!

 

Thank you for that reply.

I hadn't heard of stopPropagation and hadn't really considered event bubbling. You're reply got me reading all through developer.mozilla.org/en-US/docs/L...

My question wasn't very clear and that Mozilla link, while really useful, also doesn't answer it. So I'll try to rephrase.

If you register an event listener with a handler, you have the option of being passed the event object. When your event handler gets called, when bubbling, does the engine then check to see whether the event handler called preventDefault/stopPropagation to determine whether to pass the event object to the next event handler?

And another question. In the case of, for example, a form. When you click submit and you want to preventDefault with your handler, is there default event handler lower in the chain of progression of the event that we are then blocking, or is it something else?

The way the event gets passed between handlers implicitly seems to be confusing me.

None the less, this article and your reply have been interesting to me.

code of conduct - report abuse