edddd
edddd

Reputation: 482

Scope of Event Listeners

I have added an event listener to this button:

<button id="start" onclick="start();">Start</button>

if I define the start() function in the global scope in the js file, it works just fine.

function start() {
  console.log("start clicked");
}

But how do I avoid giving it the global scope? Would it work if I added the event listener using addEventListener in a local scope? Is there any other way? Is it bad practice to add the event listener using HTML?

Upvotes: 3

Views: 2176

Answers (1)

palaѕн
palaѕн

Reputation: 73896

It's generally not a good idea to use inline event handlers. As mentioned in the above links:

You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

It's better to use addEventListener in local scope like:

const btn = document.querySelector('#start');

function start() {
  console.log("start clicked");
}   

btn.addEventListener('click', start);
<button id="start">Start</button>

Again, as mentioned in the above links:

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers.

Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you have to do is add or remove event handlers as appropriate.

Second, you can also register multiple handlers for the same listener.

Upvotes: 2

Related Questions