Tuesday, September 18, 2018

JavaScript - Events - Event Handlers



window.onload = function() {
  console.log("Window loaded.");
};


Now, say - I have the following code snippet:
<body>
  <button>Click Here</button>
</body>

Now, let us add an onclick event on this button:

var btn = document.querySelector("button");

btn.onclick = function(){
  console.log("Button Clicked");
};

We have setup the onclick handler. On pressing the button we can see the output on the console. This is a very useful concept.

But, how can we know, which specific functions are available on the HTML element?
Technique 1: Log the element to the console and then check the properties and then we can identify the event handlers by the on* prefix on the event handler variables.
Technique 2: Google for JavaScript <<element name>> <<events >> and we can find the relevant links with information about it.

We can add the onclick event on any HTML element. We can add the onclick event on the document itself:

document.onclick = function(){
  console.log("Clicked");
};

But, there is one major disadvantage of this approach. Now, suppose we have two event handlers associated with the same button element:

var btn = document.querySelector("button");

btn.onclick = function(){
  console.log("Button Clicked");
};

btn.onclick = function(){
  console.log("Button Clicked 2");
};

Now we see only the message:
Button Clicked 2

.. on the console.

This has happened because the first event handler is simply overwritten. Hence, it is no longer available. Hence, this can become a problem as there will be times when you will need multiple listeners!

No comments:

Post a Comment