1
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("a").click(function (event) {         
            event.preventDefault();
            alert('disabled');
        });
    });
</script>
</head>
<body>
<a href="/">Go to dotnetheaven.com </a>
</body>
</html>

Here(http://api.jquery.com/event.preventDefault/), it is said: If this method is called, the default action of the event will not be triggered.

Question:

For the above code, the event means 'click'? 'the default action' is openning the URL? Am I understanding correctly? Because I wonder why alert still shows up after event.preventDefault().

Mike Campbell
  • 7,921
  • 2
  • 38
  • 51
user2507818
  • 2,719
  • 5
  • 21
  • 30
  • 2
    Yes, the default action for clicking an anchor is navigating to its `href`. – Jon Jun 24 '13 at 12:36
  • 1
    `alert` is not the default action, so why shouldn't it show up? :-) – Kilian Stinson Jun 24 '13 at 12:37
  • @KnutMarius [return false and preventDefault are not the same thing](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – jbabey Jun 24 '13 at 12:38
  • 1
    `event.preventDefault();` is not provided by jQuery. – techfoobar Jun 24 '13 at 12:39
  • @techfoobar: It is, as jQuery passes a [custom `jqEvent` object](http://api.jquery.com/category/events/event-object/) to the handler, and `preventDefault` will call the native one (or the M$ equivalent) – Bergi Jun 24 '13 at 12:51
  • @Bergi - Yes, you're right in that respect. But `preventDefault()` is available in the native event object as well, so the difference is not very significant in this case. – techfoobar Jun 24 '13 at 12:52

3 Answers3

2

For the above code, the event means 'click'? 'the default action' is openning the URL? Am I understanding correctly?

Yup.

Because I wonder why alert still shows up after event.preventDefault().

The rest of the function will still execute, event.preventDefault() does not return.

karim79
  • 339,989
  • 67
  • 413
  • 406
2

The default action is to open the URL.

event.preventDefault() will prevent this.

The alert() is not the default action, this is one you have specified (as you've put it in the click event handler). Therefore this will still action.

Matt Cain
  • 5,638
  • 3
  • 36
  • 45
Curtis
  • 101,612
  • 66
  • 270
  • 352
1

The default behaviour is to change location.href to / which is being prevented using .preventDefault(), Your event handler will continue to execute after preventing the default action.

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111