understanding how PreventDefault and DefaultPrevented work with custom events

I think you are looking at it from a user's perspective. You should think of it from a developer's perspective. Consider the following example. In this example, we are giving the user the following functionality:

  1. When the user clicks on a link our plugin will display an alert
  2. There are two possibilities:
    1. The user might use our feature (of seeing the alert)
    2. Or might want to define their own functionality.

Lets define our plugin

$('a').on('click', function (e) { // As per our feature we will act on clicking a href
    var slideEvent = $.Event('slide'); // lets create our custom event
    e.preventDefault(); // of course we don't like hrefs
    $(this).trigger(slideEvent); // We should throw a slide event when the link is clicked
    if (slideEvent.isDefaultPrevented()) { // but if the user does not want to see our default event, they will preventDefault and we should stop our feature
        alert('is default prevented');
        return;
    }
    alert('clicked on href'); // our default feature is to display alert.
});

How is this feature consumed now ?

In this case the user chooses to use the default feature and so on click clicked on href is seen.

$('#case1').on('slide', function (e) {
   // e.preventDefault();

});

In this case, the user choose to define a custom functionality and hence e.preventDefault is used. (Which is caught in our plugin's definition in isDefaultPrevented())

$('#case2').on('slide', function (e) {
   e.preventDefault();
});

Full example:

$('a').on('click', function (e) {
    var slideEvent = $.Event('slide');
    e.preventDefault();
    $(this).trigger(slideEvent);
    if (slideEvent.isDefaultPrevented()) {
        alert('is default prevented');
        return;
    }
    alert('clicked on href');
})

$('#case1').on('slide', function (e) {
   // e.preventDefault();

});
$('#case2').on('slide', function (e) {
   e.preventDefault();
});

$('a').on('click', function (e) {
    var slideEvent = $.Event('slide');
    e.preventDefault();
    $(this).trigger(slideEvent);
    if (slideEvent.isDefaultPrevented()) {
        alert('is default prevented');
        return;
    }
    alert('clicked on href');
})

$('#case1').on('slide', function (e) {
   // e.preventDefault();
    
});
$('#case2').on('slide', function (e) {
   e.preventDefault();
});
a {
    font-size: 3em;
    text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <a href="http://stackoverflow.com/" id="case1">Case 1</a>
 <a href="http://stackoverflow.com/" id="case2">Case 2</a>

Tags:

Jquery