JQuery: event.preventDefault ()

In what condition are we using jQuery: event.preventDefault (); .... where will it be used?

+3
source share
2 answers

If you want to prevent default behavior. For example, when handling a form submit event, if you want to post using ajax and not refresh the page, you should use event.preventDefault().

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

Returning falsefrom your function will usually have the same effect.

+7
source
function() {
  return false;
}

// IS EQUAL TO

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

Another very good example: href

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

the following code will show a warning and result in the default user behavior: href and www.sometst.com

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

event.preventDefault, . 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
});

SO

false jQuery , e.preventDefault and e.stopPropagation.

, , preventDefault , , .., false, .

.

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

+3

Source: https://habr.com/ru/post/1779935/


All Articles