Non-Form Events
Any element on a page can respond to the mouse, such as a click or a press of a mouse button, so even a plain div or table row can react to the user.
Apprentice · JavaScript · Updated
After this lesson you can
- Make any element respond to clicks with a click event listener
- Tell which mouse button was pressed from a mousedown event's button property
Key takeaways
- Elements send mouse events such as click, mouseover, mouseout and mousedown.
- A click listener works on any element, not only buttons. To go to another page, still use a link.
- The browser passes the handler an event object. For mousedown, its button property says which button was pressed, 0 for left, 1 for middle and 2 for right.
The events that a developer can react to are dependent on the type of HTML element a user interacts with. For example form input elements expose events that relate to user input, while display elements expose mostly mouse events.
HTML elements emit events to which developers can respond, such as click, mouseover, mouseout, mousedown, etc.
These events allow us to do things like convert common display elements into objects with which a user can interact.
click
The click event is not just for buttons, but can be attached to any HTML element, such as a div, tr, img or any other element.
A click event can make any element react to the user. (To go to another page, still use an <a href> link: it works with the keyboard, in a new tab, and without JavaScript.)
This example marks a product as selected, or unselected, each time it's clicked:
<div id="productDetail">Product Name</div>
const div = document.getElementById("productDetail");
div.addEventListener("click", () => div.classList.toggle("selected"));
mousedown
The mousedown event is fired when a mouse button is pressed. The browser passes the handler an event object with the details of what happened, and for mousedown its button property says which mouse button was pressed: 0 for the left button, 1 for the middle button and 2 for the right button.
function handleMouseDown(event)
{
if (event.button === 0)
{
console.log("Left button pressed");
}
else if (event.button === 1)
{
console.log("Middle button pressed");
}
else if (event.button === 2)
{
console.log("Right button pressed");
}
}
const div = document.getElementById("productDetail");
div.addEventListener("mousedown", handleMouseDown);
Check yourself
2 questions to try on the lesson page.
So what
With a click listener, anything on the page can become something the user works with: a product card, a table row, a photo.