Jump to content

preventDefault in Javascript


mostafatalebi

Recommended Posts

Hello everybody

 

I have searched the net but have not understood the following question's answer perfectly.

 

What is the difference between the

event.preventDefault();

and

event.stopPropagation();

in Javascript as it seems both of them deals with the default action of an element.

 

Thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/280347-preventdefault-in-javascript/
Share on other sites

preventDefault() is obvious - the default action associated with an event is prevented. In case of a click on an <a> tag, you will not be redirected to another page.

 

stopPropagation() stops the click event from propagating up to a higher hierachy element - also called "bubbling" - and prevents the click action from accidentally triggering other clicks.

For a demonstration, check: http://jsfiddle.net/9TJJP/

 

Clicking either of the icons on the end will give you an alert saying you clicked the link, but no navigation occurs because the attached event handler calls preventDefault().

 

Clicking the middle icon follows the link as expected and shows no alert. Because the event handler for it calls stopPropagation, the event handler attached to the parent A tag is never executed.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.