There are three ways: an inline HTML attribute such as onclick, a DOM property such as button.onclick, and addEventListener(). Use addEventListener() in modern code.
An inline attribute mixes JavaScript into the HTML as a string, and a strict Content Security Policy (CSP) blocks it. A DOM property keeps the code in JavaScript, but each element holds only one handler per event, so assigning a second one replaces the first.
addEventListener() lets you attach many listeners to the same event. It also accepts options such as once and passive, supports the capture phase, and pairs with removeEventListener() for cleanup.
<!-- HTML attribute -->
<button onclick="handleClick()">Click</button>
// DOM property
button.onclick = function() { };
// addEventListener (recommended)
button.addEventListener('click', function() { });
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓