Listening to events

This is possibly the best known way to bind an event listener:

myElement.onclick = function onclick(event){
  console.log(event.type +' got fired')
}

But this should generally be avoided. Here,.onclickis a property of the element, meaning that you can change it, but you cannot use it to add additional listeners — by reassigning a new function you’ll overwrite the reference to the old one.

Instead, we can use the much mightier.addEventListener()method to add as many events of as many types as we like. It takes three arguments: the event type (such asclick), a function that gets called whenever the event occurs on the element (this function gets passed an event object), and an optional config object which will be explained further below.

myElement.addEventListener('click',function(event){
  console.log(event.type +' got fired')
})

myElement.addEventListener('click',function(event){
  console.log(event.type +' got fired again')
})

Within the listener function,event.targetrefers to the element on which the event was triggered (as doesthis, unless of course we’re using anarrow function). Thus you can easily access its properties like so:

// The `forms` property of the document is an array holding
// references to all forms
const myForm = document.forms[0]
const myInputElements = myForm.querySelectorAll('input')

Array.from(myInputElements).forEach(el => { 
    el.addEventListener('change',function(event){
        console.log(event.target.value)
    })
})

results matching ""

    No results matching ""