Events
General Events
| Event | Description |
|---|---|
| click | Triggered when the user clicks on an element. |
| mouseenter | Triggered when the mouse pointer enters an element. |
Mobile Browsers
| Event | Description |
|---|---|
| touchstart | Triggered when the user touches the screen. |
| touchmove | Triggered when the user moves their finger across the screen. |
| touchend | Triggered when the user lifts their finger off the screen. |
| touchenter | Triggered when a touch point enters the bounding box of an element. |
| touchleave | Triggered when a touch point leaves the bounding box of an element. |
| touchcancel | Triggered when a touch point is interrupted (e.g., by a system alert). |
Document content loaded:
document.addEventListener('DOMContentLoaded', () => {
// ...
});
Everything is loaded
document.addEventListener('load', () => {
// ...
});
Adding event listeners
someNode.addEventListener('click', () => {
// ...
});
Run only once:
someNode.addEventListener('click', () => {
// ...
}, {once: true});
Old approaches
someNode.onclick = function() {
// First function.
}
someNode.onclick = function() {
// Second function. (First function will be overwriten)
}
In HTML:
<a href="#" onclick="func()"></a>
Delete an event listener
const deleteElement = (e) => {
e.target.remove();
};
btn.removeEventListener('click', deleteElement);
Event object
someNode.addEventListener('click', (e) => {
console.log(e); // event object
});
e.target- in case we use the same event handler for many elements, this property will have the deeper object.e.currentTarget- in case we use the same event handler for many elements, this property will have the actual object.e.type- event name.
Touches events info:
e.touches- all current touches.e.targetTouches- current touches on a target.e.changedTouches- like an example fortouchend, there will be touches that left the target.
Cancel default behavior
Examples:
link.addEventListener('click', (e) => {
e.preventDefault(); // Should be right away after beginning.
});
form.addEventListener('submit', (e) => {
e.preventDefault(); // Should be right away after beginning.
});
Old approach:
link.addEventListener('click', (e) => {
// Your code is here
return false;
});
Andrew Dorokhov