Ludwig
Ludwig

Reputation: 1801

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();
  });

Upvotes: 1

Views: 45

Answers (3)

Ifrahim Rasool
Ifrahim Rasool

Reputation: 58

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!

Upvotes: 2

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10187

First of all e.preventDefault() should be first line when defining what all things will happen in function.

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

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

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

Secondly preventDefault prevents the default function of element to which it is applied.

For ex:

<a href="#" class="clickBtn">

If you fire event on above <a> by default it will take to document to top and will show a # in url and then fire you function but if you use preventDefault then its default function of linking will be prevented.

Upvotes: 1

Justinas
Justinas

Reputation: 43479

It will prevent further default action for current event.

E.g. clicking on link will follow href of element. e.preventDefault(); will prevent following link and you will not be redirected.

More information here

$(document).ready(function() {
  $('#a1').click(function(e) {
    e.preventDefault();

    alert('Clicked, but not following link.');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com" id="a1">Link with preventDefault</a>
<br/>
<a href="http://google.com" id="a2">Link without preventDefault</a>

Upvotes: 1

Related Questions