Two JS event listener options you never knew

or at least, options I never knew

Recently I got into the habit of reading the docs instead of just reading off of StackOverflow.

I wanted to execute a function after loading the body element without using jQuery, so I went to the docs for the addEventListener method down at MDN.

I took a look at the parameters for the method and inside the options argument (3rd argument, optional) were options I never knew were there.

The options parameter, in all its glory.

The ones I am interested here are once and passive.

The once option allows you to run the specified event handler only once and then it would be removed as an event handler.

This would be more efficient than just monitoring the state of the application and having an if-statement inside your handler because the handler would still run when the event fires.

For example, I would prefer this:

element.addEventListener('click', () => {
// Do Stuff
}, {once: true});

over this:

element.addEventListener('click', () => {
if (clicks === 0) {
// Do Stuff

The passive method also saves you some lines of code by just specifying it instead of calling the preventDefault method.

For example, if you want to do a custom form submit, it would look like this:

element.addEventListener('submit', () => {
// Do Stuff
}, {passive: true});

instead of this:

element.addEventListener('submit', (e) => {
// Do Stuff

If you liked this post, click the cute little green heart below and/or follow me! Thanks for reading! 😁
Personal Pages:
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.