this object in JavaScript

Now we will work with a special object this available in the event handler function. This object points to the element where the event occurred.

The this object is useful when the element on which the event occurred and the element being acted upon as a result of the event are the same element.

For example, if we have an input, we can attach a focus loss handler to it and, upon the occurrence of this event, do something with the input text. Let's do the above. Let us have an input:

<input id="elem" value="text">

Let's get a reference to it into the variable elem:

let elem = document.querySelector('#elem');

Let's bind the blur event handler function to it:

elem.addEventListener('blur', func);

Inside this function func, an object this will be available referring to our input:

function func() { console.log(this); // contains a reference to our element }

Let's output the content of the value attribute of our input:

function func() { console.log(this.value); // displays the content of the attribute }

Well, now let's write some text to the input:

function func() { this.value = '!!!'; }

You can also use an anonymous function:

elem.addEventListener('blur', function() { this.value = '!!!'; });

Input is given. When this input receives focus, write the number 1 into it, and when it loses focus, write the number 2. To refer to an input inside a handler function, use the this object.

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.