Hitesh Prajapati
Hitesh Prajapati

Reputation: 2842

JQuery : event.preventDefault()

In which condition we use JQuery : event.preventDefault(); .... where it will be used ?

Upvotes: 3

Views: 8238

Answers (2)

kobe
kobe

Reputation: 15835

function() {
  return false;
}

// IS EQUAL TO

function(e) {
  e.preventDefault();
  e.stopPropagation();
}

one other very good example is href

<a href="http://www.sometest.com" class="justtest">
test</a>

the following code will show an alert and takes the user to its default behavior which is href and www.sometst.com

$('.justtest').submit(function(ev) {
    alert("a href click");
});

if i use event.preventDefault , it will just show the alert and stops its default behavior.it doesn't take the user to www.sometest.com

$('.justtest').submit(function(ev) {
    alert("a href click");
    event.preventDefault();// this is better 
    // return faslse// return false will kill all the events so try to use preventDefault
});

got it from SO only

Returning false from jQuery event handlers is equivalent to calling both, e.preventDefault and e.stopPropagation.

So the difference is that preventDefault will only prevent the default event action to occur, i.e. a page redirect on a link click, a form submission, etc. and return false will also stop the event flow.

see this also

http://css-tricks.com/return-false-and-prevent-default/

Upvotes: 3

sje397
sje397

Reputation: 41812

When you want to prevent the default behaviour. For example when handling a form submit event, if you want to post with ajax and not have your page refresh, you would use event.preventDefault().

$('#myform').submit(function(ev) {
    ev.preventDefault();
    // ajax stuff...
});

Returning false from your function will usually have the same effect.

Upvotes: 7

Related Questions