Hey! 👋🏼
Redi School Munich - Spring 2021
MDN: Events
document.querySelector("#theButton").addEventListener("click", () => {
console.log("Button was clicked");
});
Either with an HTML on[event]attribute:
Or with the addEventListener function:
element.addEventListener("click", () => { doSomething(); });
The following syntax also works, but isn't recommended, because it would overwrite event listeners previously added the same way:
element.onclick = function() {
doSomething();
};
click fires, when an element is clicked ondblclick fires, when an element is clicked on twice in quick successionmouseover fires, whenever the pointer moves over an elementfocus fires, when an element is focused using the tab keyblur fires, when leaving an input fieldkeydown fires, whenever a keyboard key is being pressedThe event handler receives an object called the event object, containing metadata about the event that was fired.
This object contains information based on the type of event. For example, keyboard events have a key attribute containing the key that was pressed.
myInput.addEventListener("keydown", (event) => {
myParagraph.textContent = "Caught keydown event with key " + event.key;
});
Javascript can't possibly know all ways of validating any given set of data. That's why the setCustomValidity method exists.
setCustomValidity is a method that exists on every input elementExample
const myInput = document.querySelector("input");
myInput.setCustomValidity("You can't do this!");
// The passed string is the message displayed to the user
const myInput = document.querySelector("input");
myInput.setCustomValidity(""); // Valid again
We can combine this method with the blur event to create our own validation logic
const myInput = document.querySelector("input");
myInput.addEventListener("blur", (event) => {
const valid = checkCustomPreconditions();
if (!valid) {
event.target.setCustomValidity("Custom Preconditions failed");
} else {
event.target.setCustomValidity("");
}
});