addEventListener/removeEventListener non-optional arguments Sample

Available in Chrome 49+ | View on GitHub | Browse Samples

Background

Previously, Chrome treated the first two arguments (type and listener) of addEventListener and removeEventListener optional, while they are non-optional in the spec and other browsers. This has changed: Now calling these methods with zero or one argument throws an Exception.

Live Output

Call document.body.addEventListener with no arguments.
> Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only 0 present.

Call document.body.addEventListener with one argument.
> Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only 1 present.

Call document.body.removeEventListener with no arguments.
> Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only 0 present.

Call document.body.removeEventListener with one argument.
> Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only 1 present.

JavaScript Snippet

ChromeSamples.log('Call document.body.addEventListener with no arguments.');
try {
  document.body.addEventListener();
} catch (error) {
  ChromeSamples.log('> ' + error.message + '\n');
}

ChromeSamples.log('Call document.body.addEventListener with one argument.');
try {
  document.body.addEventListener('click');
} catch (error) {
  ChromeSamples.log('> ' + error.message + '\n');
}

ChromeSamples.log('Call document.body.removeEventListener with no arguments.');
try {
  document.body.removeEventListener();
} catch (error) {
  ChromeSamples.log('> ' + error.message + '\n');
}

ChromeSamples.log('Call document.body.removeEventListener with one argument.');
try {
  document.body.removeEventListener('click');
} catch (error) {
  ChromeSamples.log('> ' + error.message + '\n');
}

// Example of valid usage:
var handler = function() {
  // Do something.
};
document.body.addEventListener('click', handler);
document.body.removeEventListener('click', handler);