Skip to content

unicorn/prefer-add-event-listener Suspicious

🚧 An auto-fix is still under development.

What it does

Enforces the use of .addEventListener() and .removeEventListener() over their on-function counterparts.

For example, foo.addEventListener('click', handler); is preferred over foo.onclick = handler; for HTML DOM Events.

Why is this bad?

There are numerous advantages of using addEventListener. Some of these advantages include registering unlimited event handlers and optionally having the event handler invoked only once.

Examples

Examples of incorrect code for this rule:

javascript
foo.onclick = () => {};

Examples of correct code for this rule:

javascript
foo.addEventListener("click", () => {});

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny unicorn/prefer-add-event-listener
json
{
  "rules": {
    "unicorn/prefer-add-event-listener": "error"
  }
}

References

Released under the MIT License.