8

Possible Duplicate:
event.preventDefault() vs. return false

I'm not sure, but as far as I see, event.preventDefault is coming from jQuery. if yes, I'm wondering is there any native equivalent in Javascript doing the same?

Community
  • 1
  • 1
Mahdi
  • 9,247
  • 9
  • 53
  • 74
  • 2
    preventDefault is a DOM method. See the W3C specification [here](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation). – PHeiberg Oct 06 '12 at 08:39
  • 1
    I don't think this question is the same as that. – Barmar Oct 06 '12 at 08:40
  • @Barmar the topic is the same and the answer is suitable in both context so what value does it bring to have both? – Rune FS Oct 06 '12 at 08:42
  • 2
    @PraveenKumar if you read that question entirely you will see they are comparing `preventDefault` to `return false` ... my question seems similar to that? – Mahdi Oct 06 '12 at 08:42
  • @PHeiberg thanks! that's what I was looking for! could you post your comment as an answer, it would be helpful for others also! :) – Mahdi Oct 06 '12 at 08:48

3 Answers3

11

preventDefault is a DOM method. See the W3C specification here.

PHeiberg
  • 29,411
  • 6
  • 59
  • 81
1

jQuery wrap around native JavaScript event object. preventDefault is JavaScript method. you can achieve preventDefault in jQuery by return false;.

Anoop
  • 23,044
  • 10
  • 62
  • 76
  • yeah, I think that's true. but what about any equivalent natively in Javascript, when we have no `jQuery`? – Mahdi Oct 06 '12 at 08:38
  • @Mahdi preventDefault is related to JavaScript not jQuery. – Anoop Oct 06 '12 at 08:39
  • 2
    if you return false from a jQuery event handler it's equivalent to calling both preventDefault **and** stopPropagation. it's not the same as calling preventDEfault _only_ – Rune FS Oct 06 '12 at 08:43
  • jQuery return false is take care of preventDefault as well as stopPropagation. preventDefault means stop default behavior of action eg clicking on link should not open the link. while stopPropagation is to stop other listener to listen this event. – Anoop Oct 06 '12 at 08:46
0

return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.

e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Source: https://stackoverflow.com/a/1357151

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252