Marco Marco - 7 months ago 55
Javascript Question

Javascript - jQuery preventDefault method

I am a javascript noob, so apologies if this question is not for this forum. I am trying to understand jQuery method:


e.preventDefault()


In the code below, when moving items form one list to another it is needed for us to be able to move the items. I would like to know what exactly is happening there and what default action are we preventing from happening?

$('#move').click(
function(e) {
$('#list1 > option:selected').appendTo('#list2');
e.preventDefault();
});

$('#moveAll').click(
function(e) {
$('#list1 > option').appendTo('#list2');
e.preventDefault();
});

$('#removeAll').click(
function(e) {
$('#list2 > option').appendTo('#list1');
e.preventDefault();
});

Answer

Well basically when you click hyperlink it posts back to url or # When we add e.preventDefault() function, jQuery will prevent default action of click event.

Therefore when you click #move, page will not refresh but action within function will be executed.

Hope this helps!

Comments