click
The most common event. It fires when an element is clicked with a mouse, tapped on a touch screen, or activated with the keyboard (Enter or Space on a button).
<button id="b">Click me</button>
<p id="out"></p>
<script>
document.querySelector("#b").addEventListener("click", () => {
document.querySelector("#out").textContent = "Clicked at " + new Date().toLocaleTimeString();
});
</script>
Other mouse events
| Event | When |
|---|---|
dblclick | double click |
contextmenu | right click (or the menu key) |
mousedown, mouseup | button pressed / released |
mouseenter, mouseleave | pointer enters / leaves the element (does not bubble) |
mouseover, mouseout | like the above, but they bubble and also fire for children |
mousemove | pointer moves |
Hover effects
If a hover is only visual, CSS :hover is better. Use events when you need to run code.
<style>
.tile { width: 120px; height: 60px; background: #1a5276; color: white; display: grid; place-items: center; }
</style>
<div class="tile" id="tile">Hover me</div>
<script>
const tile = document.querySelector("#tile");
tile.addEventListener("mouseenter", () => { tile.textContent = "Inside"; });
tile.addEventListener("mouseleave", () => { tile.textContent = "Hover me"; });
</script>
Where was the click?
The event object carries coordinates (see The Event Object).
<div id="area" style="height:80px;background:#fdf2e9;padding:8px">Click anywhere in here</div>
<p id="pos"></p>
<script>
document.querySelector("#area").addEventListener("click", event => {
document.querySelector("#pos").textContent = `x: ${event.offsetX}, y: ${event.offsetY}`;
});
</script>
Pointer events
For code that should work with mouse, touch and pen alike, use pointer events: pointerdown, pointermove, pointerup. They are the modern replacement for separate mouse and touch events.
Touch screens
There is no hover on phones. Do not make important content depend on mouseenter. A tap triggers click, so use that.
Keyboard users
click fires for keyboard activation of buttons and links, which is another reason to use real <button> elements instead of listening for clicks on a <div>.