Unbinding events in JavaScript

In this lesson, we will learn how to unbind event handlers that we previously attached to elements. Let the following button be given as an example:

<input id="button" type="submit">

Bind the function func to this button:

let button = document.querySelector('#button'); button.addEventListener('click', func); function func() { console.log('!!!'); }

Let's now make the event handler fire on the first click, and then unbind from the button. There is a special method removeEventListener for this. This method takes the type of the event as the first parameter, and the reference to the function to be unbindable as the second parameter.

Typically, this means that the event handler is unbound the same way it was bound. That is, if we bind it like this: addEventListener('click', func), then we will unbind it with the same parameters, like this: removeEventListener('click', func)ā…/ cā†.

So let's solve our problem:

let button = document.querySelector('#button'); button.addEventListener('click', func); function func() { console.log('!!!'); this.removeEventListener('click', func); }

Given a link and a button. On button click add to the end of the link text the value of its href attribute in parentheses. Make it so that this addition occurs only on the first click.

Given a button whose value is the number 1. Make it so that when you click on this button, its value increases by one each time. After the button's value reaches 10 - unbind the event handler so that the button no longer responds to pressing.

© learn.itnots.ru