click
event with the addEventListener
function:const handler = () => {console.log('the element is clicked');};element.addEventListener('click', handler);
onclick
property or inline onclick
attribute such as:element.onclick = handler;<div onclick="handler()" /><div onclick="javascript: handler()" />
addEventListener
.on___
property or attribute allows to register only one handler. Setting on___
will remove all existing handlers.onclick is used
in Console because the onclick
removes the original handler
.const handler = () => {console.log('addEventListener is used');};element.addEventListener('click', handler);const anotherHandler = () => {console.log('onclick is used');};element.onclick = anotherHandler;
addEventListener
, it's possible for us to handle the event in either capturing or bubbling phase by passing.
The on___
property doesn't support that.div
element as following:<div id="parent">Parent<div id="child">Child</div></div>
click
event:const handleParentClick = () => {console.log('parent is clicked');};const handleChildClick = () => {console.log('child is clicked');};
addEventListener
to true
or false
could change the order of handler execution.// We will see "child is clicked" and then// "parent is clicked" when clicking the child element// The `click` event is passed from the bottom node// up to its parentsdocument.getElementById('parent').addEventListener('click', handleParentClick, false);document.getElementById('child').addEventListener('click', handleChildClick, false);
click
event is passed from parents down to its children:// We will see "parent is clicked" and then// "child is clicked" when clicking the child elementdocument.getElementById('parent').addEventListener('click', handleParentClick, true);document.getElementById('child').addEventListener('click', handleChildClick, true);
addEventListener
function doesn't work before Internet Explorer (IE) 9, while onclick
is supported by all browsers.
The IE 8 and older versions use the attachEvent
function.element.attachEvent ? element.attachEvent('onclick', handler) : element.addEventListener('click', handler);
addEventListener
onclick
attribute. It has a potential security issue since we pass a string.
The browser also doesn't warn if the method passed to onclick
attribute doesn't exist.<button (click)="sayHello()">Hello</button>
<button onClick={sayHello}>Hello</button>
<button v-on:click="sayHello">Hello</button>
onclick
attribute, the framework parses the code, and transpiles it to addEventListener
method.const handler = (e) => {...};// Attach event listenerelement.addEventListener('click', handler);// Remove it laterelement.removeEventListener('click', handler);
class Resize extends React.Component {const handleResize = (e) => {...};componentDidMount() {window.addEventListener('resize', this.handleResize);}componentWillUnmount() {window.removeEventListener('resize', this.handleResize);}}