Home > Back-end >  ESLint warning event is defined but never used
ESLint warning event is defined but never used

Time:01-08

I'm getting an error with ESLint on this simple bit of code:

var trigger = document.getElementById("hello");
var audio = new Audio('audio/hello.mp3');

window.addEventListener('DOMContentLoaded', (event) => {
    trigger.addEventListener("click", function(event) {
        event.preventDefault();
        audio.play();
    }, false);
});

The error I'm getting is: 'event' is defined but never used.

I've read that I can disable this error by adding a comment after the open brace where 'event' is used like this: // eslint-disable-line no-unused-vars.

But my question is, is anything actually wrong with this code and should it be fixed or improved on? Rather than covered up by a comment ignoring the warning? Or is there actually nothing wrong with this approach and it's just ESLint being pedantic?

CodePudding user response:

But my question is, is anything actually wrong with this code and should it be fixed or improved on?

You're never using the event parameter you define in the DOMContentLoaded event listener (you're only using the one defined in the click handler), so you should remove it:

window.addEventListener('DOMContentLoaded', () => {
// No `event` here −−−−−−−−−−−−−−−−−−−−−−−−−−^

Having said that, though, using DOMContentLoaded is unnecessary if you control the script tag that loads the code. If you do, just use type="module" or defer to ensure the code doesn't run until the DOM is built.

CodePudding user response:

Linters can be annoying, but it’s usually a good idea to try and keep them happy. Instead of disabling the warning, though, you can indicate that you are deliberately ignoring a parameter by beginning its name with an underscore.

var trigger = document.getElementById("hello");
var audio = new Audio('audio/hello.mp3');

window.addEventListener('DOMContentLoaded', (_event) => {
    trigger.addEventListener("click", function(event) {
        event.preventDefault();
        audio.play();
    }, false);
});

You can also use just an underscore for the parameter name, or leave it out completely.

  • Related