Understanding JavaScript Events: Click, Submit, Keypress, and More
All you need to know to handle events properly in JavaScript as a Junior Dev
Hey Junior Dev,
I'm sure you know what events are in JavaScript, and you might have used some of them before. But what are they exactly? Well, Events in JavaScript are simply just actions that happens when we interact with a website in the browser.
That's it! But how can you tell when an event occurs? Good question. We can use something called event listeners. They wait and "listen" until the event they are watching for happens or is triggered. It's a powerful way to make web pages interactive by responding to user actions or other events. Got it? Okay, let's dive deeper. ๐
Some simple terms you need to have in mind to understand the code snippets youโll soon see:
Event Listener: This is an inbuilt browser API that helps you listen for events. By listen, we mean just sitting in the background and waiting until the event happens. Got it?
Event Handler: This answers the question โWhat happens when the event happens or is triggered?โ Well, our event handler will always have a nice little handler that will detect when an event is triggered and boom! It calls the handler, which is usually just a function that does whatever we want. Interesting, right?
But what are events themselves? They are simply actions or occurrences that happen in the browser when we interact with a website. Here are some common examples:
onclick: Fired when the cursor is clicked twice on an element.
onmouseover : Fired when the mouse pointer moves over an element.
onmouseout: Occurs when the mouse pointer leaves an element.
onkeydown: Fired when a key is pressed down.
onkeyup: Fired when a key is released.
onchange: Triggered when the value of an input element changes.
onload: Occurs when a page has finished loading.
onsubmit: Fired when a form is submitted
Here are some simple code snippets showing how to use โaddEventListener()
โ to wait for and handle events.
Your index.html should look like thisโฆ
<!-- Lets just assume we have a form, button and a select element in our html file we want to add an event listener to !-->
<form id="letterForm">
<input id="inputLetter" />
<select id="selectLetter">
<option selected disabled>Choose Letter</option>
<option value="a">Choose A</option>
<option value="b"> Choose B</option>
</select>
<button id="button" type="submit"></button>
</form>
<script>
//All your javascript code goes here
</script>
Creating variables for the button and select elements ๐
const button = document.querySelector('#button');
const selectLetter = document.querySelector('#selectLetter');
const letterForm = document.querySelector('#letterForm');
const inputBox = document.querySelector('#inputLetter');
Event listener to listen and wait for when the document finishes loading ๐
document.addEventListener('load', () => {
alert('The site has loaded successfully!')
});
Event listener to listen and wait for when the user clicks on the button ๐
button.addEventListener('click', () => {
// This is where you handle the event, could be anything you want: from DOM Manipulation to CSS styling
});
Alternative way of doing this is calling the event listener directly ๐
//Alternative way
button.onclick = () => {
// This is where you handle the event, could be anything you want: from DOM Manipulation to CSS styling
});
//Note that I personally don't like this approach even though it looks easy to listen to event for one element.
//This easy quick approach is not able to add multiple events listeners at once to an element
Event listener to listen and wait for when the user clicks on the select element and choose an option ๐
button.addEventListener('click', () => {
// This is where you handle the event, could be anything you want: from DOM Manipulation to CSS styling
});
Side Note: Please remember when to use and when not to use e.preventDefault()
Usinge.preventDefault()
stops the default behavior, allowing only our custom logic to run.
In real codebases, you might see "event" written as just "e" instead of "event." I used "event" here because this is an educational blog, and I want you to understand everything clearly.
An example of using e.preventDefault()
๐
button.addEventListener('click', (event) => {
event.preventDefalut();
// This is where you handle the event, could be anything you want: from DOM Manipulation to CSS styling
});
//In real code bases you might come across this as just 'e' instead of event.
//I only used event because this is a educational blog and I want you to understand things properly.
Having a good time? Letโs proceed to adding an event listener to listen for when we submit the form using what we already know
letterForm.addEventListener('submit', (e) => {
e.preventDefault(); //This prevents the form from submitting and reloading the page as usual
console.log(`Selected Letter is: ${selectLetter.value}`); //Our own Logic is run instead
});
Event Handling seems pretty easy right? Well, letโs do something more. Weโre going to listen for when a user changes the select option.
selectLetter.addEventListener('change', () => {
console.log(`Letter changed to: ${selectLetter.value}`);
});
Notice how I didn't use e.preventDefault()
here? That's because when we change an option, the value of selectLetter
changes as well. Using e.preventDefault()
would interfere with that. Now you know why you shouldn't use e.preventDefault()
carelessly.
Let's add an event listener to detect when we press the Enter key while typing in the input field.
inputLetter.addEventListener('keypress', (event) => {
if(event.key === "Enter") {
console.log(`Letter in inputted is: ${inputLetter.value}`);
}
});
Now for the fun part, what if we want to listen to multiple events all at once? Let's see how we can achieve this by using the input element as an example.
const events = ['click', 'mouseover', 'mouseout'];
events.forEach(event = {
inputLetter.addEventListener(event, () => {
console.log(`Hey seems liked you did a ${event} event`);
});
})
This will listen for all the events in the events array at the same time and handle them as well.
By now, you should be able to listen to and handle events properly in your JavaScript code. Okay, bye! Go ahead and have fun with those events.