Design Development JavaScript

JavaScript 101-#17 – Getting to know JavaScript events

Table of Contents

Because we are in the middle of working on custom form which requires some more advanced skills in JavaScript, let’s take a look at one topic that is very important to know. If you are familiar with jQuery and wrote some code with this library, you already got in touch with our today’s subject. What are we going to talk about are JavaScript events. Without further ado, let’s learn something more about them …

What

Any time when user interact with website, some kind of event is triggered. This goes even deeper. When whole page is loaded, this too, is an event. When page is closed … Also event. Now you should understand how those annoying pop-up windows works. Yes they are triggered by particular events happening on the page. However, you can use these events no just to make this crap, but also to create various user-friendly modification to page. Since there are many available events, we will discuss them only in broader way with few examples.

How

There are couple ways you can use to “watch” for certain event happening in order to execute some prepared code. You can either define those events in your HTML file by using event name you want to watch for as an attribute on element along with function containing code for execution. On the other hand, you can control everything via JavaScript file and not contaminate your HTML code with it.

Let’s say you have a landing page with input field for email address and button to submit this address to your mailbox. Every time email is submited you want to display “Thank you” message to user. So, we will create a new form with id of “js-form”, action attribute of “submit.php” and method attribute set to “post”. Id will be used for JavaScript. Method set to “post” basically means that form is sending some kind of data to server and PHP file in specified in action attribute takes care about what data are being sent and in what form. Inside this form will be nested two elements. First is input with type attribute set to “email”, placeholder of “Enter your email address” and don’t forget the “required” attribute. We can also add id of “js-email” to create some JavaScript controller for this input later on. Second element will be button with type attribute set to “submit”, id “js-button”, value of “Submit” and role “button”.

HTML:

<form id=”js-form” action=”submit.php” method=”post”>
 <input id=”js-email” type=”email” placeholder=”Enter your email address” required />
 <button id=”js-button” type=”submit” value=”Submit” role=”button”>Submit<>
</form>

With this setting we can now move to JavaScript and prepare the code for creating “Thank you” message. To get this done we can use two different events binded to two different elements. First option is “onclick” event tied to button element. Second is “onsubmit” event tied to form element. Let’s try both of them starting with “onclick”. In your JavaScript file create new variable “button” and associate it with button element using “document” object and “getElementById()” method with “js-button” as a parameter. On the next line use this variable followed by dot, “onclick” event, equal sign and new function. This function will not take any arguments. To display a popup every time user clicks the button use “alert(“Thank you”)”.

JavaScript:

var button = document.getElementById(“js-button”);
button.onclick = function() {
 alert(“Thank you”);
}

For the second option let’s create new variable called “form” and associate it with our form element, again, by using “document” object and “getElementById()” with “js-form” as parameter. In this case we will use “onsubmit” event instead of click (you can try click too, but it would not work exactly how we want). The syntax will be almost same as before, just change the event name.

JavaScript:

var form = document.getElementById(“js-form”);
form.onsubmit = function() {
 alert(“Thank you”);
}

Now the message will be displayed only when the form will be submitted after proper validation, which is much better solution than on every click. In case we want to use JavaScript in our HTML we will write these events as and attributes with code for execution as value.

The first option:

HTML:

<form id=”js-form” action=”submit.php” method=”post”>
 <input id=”js-email” type=”email” placeholder=”Enter your email address” required />
 <button id=”js-button” type=”submit” value=”Submit” role=”button” onclick="alert('Thank you!')">Submit<>
</form>

Or the second option:

HTML:

<form id=”js-form” action=”submit.php” method=”post” onsubmit="alert('Thank you!')">
 <input id=”js-email” type=”email” placeholder=”Enter your email address” required />
 <button id=”js-button” type=”submit” value=”Submit” role=”button”>Submit<>
</form>

However, there is another – third – way we can go. It will need learning one new method. This method is called “addEventListener()” and it allows us to “listen” to various events that are specified as parameters for this method. Function containing code to be executed is then used as a second parameter. To understand this method better let’s modify previous JavaScript code we used for button and form to suit this option.

In both cases we will again use dot notation, but now with “addEventListener()” method instead of “onclick” and “onsubmit” event. These events will be used as parameters in a form without “on” prefix – “click” and “submit”. They will be followed by comma and function with “alert(“Thank you!”)”. The result will look like this:

JavaScript:

// First option:
var button = document.getElementById(“js-button”);
button.addEventListener('click', function() {
 alert(“Thank you!”);
});
// Second option:
var form = document.getElementById(“js-form”);
form.addEventListener('submit', function() {
 alert(“Thank you!”);
});

As you can see, three different ways and all of them lead to Rome as that saying goes. In most cases the only thing that will help you decide what approach to use will be your taste and coding style. Personally, I prefer to keep HTML and JavaScript code separate.

As I mentioned in the beginning, you can know these events from jQuery. The most common is probably “click()” event. I would guess that almost every snippet of jQuery code contain at least one “click()” event. The events we used in our examples can be found in jQuery API as “click()” and “submit()” so if you like programming in jQuery more, you can easily rewrite the code to jQuery.

jQuery:

// First option:
$('#js-button').click(function() {
 alert(“Thank you!”);
});
// Second option:
$('#js-form').submit(function() {
 alert(“Thank you!”);
});

Summary

JavaScript events is one of the things every web developer and designer should know. Everything happening on website, from loading to closing the page, is some kind of event. JavaScript events can offer more opportunities to customize and personalize the content of your website to suit the users and their behavior.

You can find whole reference with all available JavaScript events on W3School website.

If you liked this article, then please consider subscribing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.