- An HTML web page has finished loading
- An HTML input field was changed
- An HTML button was clicked
Here are some common HTML events:
onchange- An HTML element has been changed
onclick- The user clicks an HTML element
onmouseover- The user moves the mouse over an HTML element
onmouseout- The user moves the mouse away from an HTML element
onkeydown- The user pushes a keyboard key
unload- The browser has finished loading the page
<button onclick="displayDate()">The time is?</button>
In summary, this section explained how to use events in HTML elements.
Events is the fundamentals to how modern framework achieves data bindings. Angular 1.x is probably the best example, its two way data binding on the lowest level is events.
event = new Event(typeArg, eventInit);
typeArg is a DOMString representing the name of the event.
evenInit is optional object type, that can take in the following:
bubbles- A boolean indicating whether the event bubbles. Default value is
cancelable- A boolean indicating whether the event can be canceled. Default value is
composed- A boolean indicating whether the event will trigger listeners outside of a shadow root. Default value is
// create a look event that bubbles up and cannot be canceled
There are times when you want to stop an event from doing what it. My most recent experience was, closing an menu when the user clicks anywhere else on the screen. So the code logic was:
- Click anywhere on the screen and hide menu
- When click on the menu, override the above logic and do not hide menu
So now the question is how do we override an event? There are a number of ways to achieve this, we will try to cover most of them here.
preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls
stopImmediatePropagation(), either of which terminates propagation at once.
Usage: Prevent a user from checking a checkbox.
Tip: If an event is not
preventDefault() will throw errors. It is recommended to check on
cancelable before invoking
Prevents further propagation of the current event in the capturing and bubbling phases.
Prevents other listeners of the same event from being called. It is the same as
event.stopPropagation() plus preventing other registered event handlers on the same element to be executed. So it does not prevent the default action for an event, such as following a clicked link.
Return false as an event is basically the same as calling both,
Tip: return false does not prevent the event from bubbling up in “normal” (non-jQuery) event handlers but still prevents the default action.