preventDefault() Method

This is an "event" method. Actually it is quite clever, the thing is I am not sure how you would be aware of it unless you had been on an advanced ECMAScript training course. I came across it when looking at a JSON page search. At first I was a little perplexed but it now makes a little more sense as the example added EventListeners to form elements on the page.

  document.addEventListener('submit', handleSearch);
  document.addEventListener('reset', function(event){
    event.preventDefault();
    render(books);

The preventDefault() is also used before the hamdlesearch code. This is to prevent the search being made unless the form element was submitted. i.e. not when the page is loaded.

  var handleSearch = function(event) {
    event.preventDefault();

What MDN say:

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

Propargation of events

The response to an event, such as a mouse click, can be prevented

stopPropagation()

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method.

stopImmediatePropagation()

The stopImmediatePropagation() method of the Event interface prevents other listeners of the same event from being called.

If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. If stopImmediatePropagation() is invoked during one such call, no remaining listeners will be called.

Links

External Sources

preventDefault() Method