First steps into JavaScript – a practical guide 3

Handling DOM events

by Iveta Karailievova Date: 07-05-2020 javascript DOM events user input validation event handlers


After we learned the basic of accessing DOM elements and how to modify them, we are ready for the more exciting parts – handling DOM events.

This allows us to make our web way more interactive, and finally we can put our JS knowledge into practice. User input such as keyboard actions or mouse clicks happens one by one and in real time and our web page is expected to respond to it as it happens. This means that web browsers thanks to functions called event handlers actively notify our code when an event is fired.

But first we need to understand in what those DOM events actually consist.

DOM events

Events are signals, that something has happened. In our case, this means that some object in the DOM has generated this kind of signal, but depending on what triggered it, we can group events into different categories. Here is a list o a few:

  • Mouse events (click, dblclick, mousewheel, contextmenu, mouseover / mouseout, mousedown / mouseup, mousemove)
  • Keyboard events (keypress, keydown, keyup)
  • Form element events (submit , focus, blur, change)
  • Window element events (scroll, resize, hashchange, load, unload)
  • CSS events (transitionend – when a CSS-animation finishes)
  • Touch events - triggered on touch devices like smart phones, tablets (touchstart, touchmove, touchend, touchcancel)
  • Hint: The names of those properties are case-sensitive, so remember to always use “onclick” and not “ONCLICK”.

Event handlers

Alright, so now we know which events to look for. But how can we react in case an event is triggered? By using event handlers, functions that get executed in case an event is triggered. They are responsible for pairing the DOM element with the event.

There are different ways of assigning those handlers. We will take a look at the the most common and preferred way, which is to use the addEventListener method. This method, in comparison to the other options of how to assign handlers, allows you to add an unlimited number of handlers.

Complementing the addEventListener method, we have the removeEventListener . Which is used to unregister a handler.

Let’s see a simple example of how assigning a handler looks like:

The addEventListene method takes two arguments: the event to listen for and the function to be executed when that event is emitted. Let's start with an example: adding a click listener to a button.

myButton.addEventListener('click', () = {
myButton.classList.add(''text-white');
}
);

This example shows us how to change the style of a button after it was clicked. (The event we listen for, in this case, is ‘click’).But what are these events?

Event objects

Every time a user interacts with his web browser, the browser creates an event object. These objects hold additional information about the event, such as their related data and functionality as properties and methods.

One of those properties is the target event property. It returns the element that triggered the event, this means the element on which the event originally occurred.

Here are some usage examples:

  • If we want to know which element triggered a specified event, we can use the event.target property together with the element.tagName property:
  • If we want to know which mouse button was pressed, we can look at the event object’s ‘button’ property.
  • If we want to know the exact coordinates where a mouse event happened, there is an event object property we can use to obtain them.

OK, that’s enough theory, now let’s practice and use our knew knowledge with validating user input.

Changing input field’s style during user data input

Imagine we have a simple form, where the user is supposed to enter a password of his choosing, but we require that its length be between 5 and 10 characters. As we already know, the input event gets triggered every time data is entered into the input element. So, even during the time that the user is entering his password, character after character, we can set the event listener so that the form dynamically shows the user (using the color of the inputs border) if his password meets the requirements. In other words, we change the style of the input element from red border to green border). How do we proceed?

Our simple and most basic HTML markup could look for example like this;

<form>
<input id="password-input" type="password" />
<form>

And now for the JS part:

First we need to get access to the input element, so we create a constant which hold a reference to the input element by calling the getElementById function.

const password = document.getElementById('password-input');

Now, we want to capture the event object, so we add an event listener to the input field. Then we add a conditional statement that checks the length property of $event.target.value and changes the border using the style property.

password.addEventListener('input', ($event) =>{
  if($event.target.value.length >= 5 && $event.target.value.length <= 10 ){
     password.style.border = "1px solid green"; 
    } else {
      password.style.border = "1px solid red"; 
    }
});

And that’s how we can give the user visual feedback when he enters data.

Changing submit button’s attribute during user data input

The exercise we did so far was simple and easy. But it doesn’t really prevent invalid data to be submitted. How about we add a submit button, with a “disabled” attribute? We can then use a similar approach as we did with the borders to change its state to enabled when our requirements are met.

Now we add a submit button to our HTML part and it looks like something this:

   <form>
      <input type="password" id="password-input">
      <button type="submit" id="submit-button" disabled="true">Submit</button>
</form>

Our little script will grow a bit: similar to how we did before, we save a reference to the DOM elements we want to access in constants. Apart from the input field, we also need to gain access to the form button:

  const password = document.getElementById('password-input');
const button = document.getElementById('submit-button');

Now, in the following lines of code, we, as before, capture the event object which gets triggered upon every data input from the user, and then we access the value of the length using the target property. 

  password.addEventListener('input', ($event) =>{
  if($event.target.value.length >= 5 && $event.target.value.length <= 10 ){
     button.removeAttribute("disabled"); 
    } else {
      button.setAttribute("disabled","true"); 
    }
});

The code in the else statement makes sure the attribute is set to disabled and only when our conditions are met, we remove the disabled attribute from our submit button. Otherwise, It is interesting to observe that instead of setting the attribute to false, we rather use the removeAttribute method.

Changing input field’s style after user data input

To complete our simple user input validation scripts, we can add another interesting yet simple feature. Imagine we need to check if two input fields match, like it happens when we want the user to chose a password and then to repeat the same password to make sure he didn’t make a type-o in the first input field.

This validation needs to happen after both input fields are filled out, so the event which suits our needs most is “blur”, which gets fired when the element is out of focus (the user tabbed or clicked away from the input field).

The HTML part for our purposes can be as simple as this:

    <form>
              <input type="password" id="password-input">
              <input type="password" id="confirm-password">
 </form>

Now to our script:

Similar as we did before, we access our input fields and store the reference:

  const password1 = document.getElementById('password');
const password2 = document.getElementById('confirm-password');

Then we attach a blur event listener to our second password input field and add the condition of the two password being equal.

Here we don’t need to capture the event, because we do not need it to check if our condition is met, we only need to compare the two passwords’ input values.

  password2.addEventListener("blur", ()  =>{
if(password1.value === password2.value){
   password1.style.border = "1px solid green"; 
   password2.style.border = "1px solid green"; 
} else{
   password1.style.border = "1 px solid red"; 
  password2.style.border = "1 px solid red"; 
} 
});

Conclusion

To make our web pages more interactive, we familiarized ourselves with concepts like events and event handlers. An easily understandable and practical way of learning how to use events is by writing simple scripts to validate user input.

Image by StockSnap from Pixabay
 
by Iveta Karailievova Date: 07-05-2020 javascript DOM events user input validation event handlers hits : 1800  
 
Iveta Karailievova

Iveta Karailievova

Originally coming from a marketing background, decided to turn her life around and immerse herself into the wonderful exciting and most importantly – never boring world of technology and web development. Proud employee at MA-NO . Easily loses track of time when enjoying working on code. Big fan of Placebo, cats and pizza.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration