The motivation of the web development is to provide a web experience that provides pages of information and allows a way for users a way to interact with the information. Javascript serves as the backbone of web in making web pages interactive through events.
A javascript event is an action that happens after you interact with elements on a web page like clicking a button or typing into a form.
Javascript is responsible for three parts as it relates to events. The first is recognizing events, manipulating the DOM(document object model), and sending messages to the server.
Event Listeners
The work of adding events to pages may call this eventing and starts with adding an event listener to an element.
The event listener recognizes whenever a user interacts with the attached element.
It consists of an event type and a callback function that is invoked after the event is triggered.
<!- Adding an event listener ->
<button>Shiny Button</button>
// First, we grab our button element.
const shinyButton = document.querySelector("button");
// Next, we attach our event listener with a click event.
shinyButton.addEventListener("click", () => {
console.log("Clicked!");
});
Event Handler
The event handler is identified by the function in the event listener that handles what to do with an event after the event listener is triggered.
// Here are using a event to alert any key event
window.addEventListener("keydown", event => {
// We are now inside the event handler
alert(`You pressed key: ${event.key}`);
});
Event Object
The event is represented by a javascript object that contains helpful properties like the event target and the event type. The event object is passed through the event listener to the event handler.
Eventing in Action
<!- Creating an name input form ->
<form id="form">
<label>Name: <input type="text"></label>
<br><br>
<button type="submit">Submit</button>
</form>
<!- We will display a name here ->
<p id="name"></p>
// Adding the event handler
function onSubmit(event) {
event.preventDefault();
name.textContent = `Hi ${event.target.value}!`;
}
// Adding the event listener
const form = document.getElementById('form');
const name = document.getElementById('name');
form.addEventListener('submit', onSubmit);
Let's chat about Events
Javascript events make up an important part of the web and we've covered a few ways of working with events. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with javascript events.
Happy Coding,
Terry Threatt
Top comments (0)