Reputation: 46222
I have the following code to just test how the e.preventDefault() works. I would think it would stop the click event from happening.
$(document).ready(function( )
{
$("button").click(function(e)
{
e.preventDefault();
alert('button clicked');
});
});
I have a button. What is the purpose of e.preventDefault(). From what I read, it will prevent the action which in this case is the click.
Note that in the above example, the alert message still show. How does e.preventDefault() work for a button click. I know if it was a hyperlink, it would prevent the hyperlink from going to it target.
Upvotes: 4
Views: 19743
Reputation: 692
$.preventDefault();
will prevent the 'Default' action from happening. For instance if you take an anchor link that already has an href
assigned to it and then add the preventDefault();
to said anchor it will no longer link.
Upvotes: 0
Reputation: 10248
You need to remember that without adding your own Click callback function there is still an Event that will fire in the browser - e.g. for an "a" tag this would be to load the URL in the href attribute, for a submit button it would be to Post/Get to the URL in the Form "Action" attribute - in both cases e.preventDefault() would stop this happening
Upvotes: 0
Reputation: 1990
What it prevents is that DOM object receiving the "click". So, if you're button was to submit a form, it won't submit it now. The alert()
afterwards will be executed regardless since you're saying, hey! stop the click, and then do this!
More Reading
Upvotes: 0
Reputation: 437336
It cannot stop the click from happening because what you have set up there is an event handler that executes after the event has triggered.
Upvotes: 0
Reputation: 12815
preventDefault is to prevent default, browser action. So if you will put something like:
$("a").click(function(e){e.preventDefault();})
click on links will do nothing. Or on submit button - form won't be submitted
Upvotes: 8