Preventing default actions

Note thateventis always available within the listener function, but it is good practive to explitly pass it in anyway when needed (and we can name it as we like then, of course). Without elaborating on theEventinterface itself, one particularly noteworthy method is.preventDefault(), which will, well, prevent the browser’s default behavior, such as following a link. Another common use-case would be to conditionally prevent the submission of a form if the client-side form-validation fails.

myForm.addEventListener('submit',function(event) {
 const name = this.querySelector('#name')

 if(name.value ==='Donald Duck') {
    alert('You gotta be kidding!')
    event.preventDefault()
 }
})

Another important event method is.stopPropagation(), which will prevent the event from bubbling up the DOM. This means that if we have a propagation-stopping click listener (say) on an element, and another click listener on one of its parents, a click event that gets triggered on the child element won’t get triggered on the parent — otherwise, it would get triggered on both.

Now.addEventListener()takes an optional config object as a 3rd argument, which can have any of the following boolean properties (all of which default tofalse):

  • capture: The event will be triggered on the element before any other element beneath it in the DOM (event capturing and bubbling is an article in its own right, for more details have a look here )
  • once: As you might guess, this indicates that the event will get triggered only once
  • passive: This means thatevent.preventDefault()will be ignored (and usually yield a warning in the console)

The most common option is.capture; in fact, it is so common that there’s a shorthand for this: instead of specifying it in the config object, you can just pass in a boolean here:

myElement.addEventListener(type, listener,true)

Event listeners can be removed using.removeEventListener(), which takes the event type and a reference to the callback function to be removed; for example, theonceoption could also be implemented like

myElement.addEventListener('change', function listener (event){
  console.log(event.type +' got triggered on '+ this)
  this.removeEventListener('change', listener)
})

results matching ""

    No results matching ""