Jump to content

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

Edited by mostafatalebi
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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.