1

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

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this confused me a bit since my hyperlink had an empty href="" so I thought it wouldn't refresh the page anyway, thanks again for the explanation!
1

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>

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.