|

JavaScript Events Tutorial

javascript events

We’re getting a good foundation on what JavaScript is all about so far with our study of the basic syntax, types, objects, and the Document Object Model. Where things start to get more interesting is when we begin to work with events. JavaScript is perfectly suited for dealing with an event driven style of programming. Learning How to Use jQuery Event Handling is also a great approach to dealing with JavaScript events – but it is important to know the underlying technology. With this approach, we can do amazing things with JavaScript, so let’s jump right in!


Events and Listeners

Having the ability to react to what the user is doing is one of the main benefits of events and listeners. Maybe we want to take an action when a user clicks a certain link, or fills out a particular form field, or simply moves their mouse to a different location. All of these things are triggering events on the user’s behalf, and we can write code to handle them.

What is an Event?

JavaScript events are actions that happen on their own. The events are happening all the time, JavaScript simply listens for the ones you specify, and then you can take some action. For example all of the following are events

  • When the page loads
  • When a user moves her mouse
  • When the user clicks a button
  • When the user scrolls the page
  • When the user clicks a form field
  • Every key press is an event
  • Events are happening at all times!

It is you, the programmer, that will decide which ones you want to take action on. The events are built right into JavaScript and there are keywords that describe them. They are lowercase and usually start with on. For example, these are all JavaScript events:

  • onload
  • onclick
  • onmouseover
  • onblur
  • onfocus

We as programmers do not write the event itself, we write the event handler. Basically, we write a JavaScript function, which is the event handler, and this function will handle an event when it happens.

Here are three different ways to respond to events in JavaScript.

Inline JavaScript

I would not recommend using this approach, but it does exist so we’ll talk about it for the sake of completeness. Just like you can place CSS inline in your HTML, so to can you place JavaScript inline. As you probably are well aware, it is always best to place your CSS in it’s own file, and JavaScript is no different. Let’s look at how to do something inline though, just to check it out.

inline javascript event handler
Here we simply give our a tag an onclick event handler, and yes, we simply run an alert box to prove it’s doing something.

Element dot Event Syntax

The second way to handle events is to use the syntax of specifying the element, then using the dot . operator syntax to choose an event. There are many free IDEs or Integrated Development Editors that can help you with auto complete tips for using this. For example, in this snippet we use the very slick Adobe Brackets to help us with auto complete. As soon as we begin typing the name of the element, then type the dot, a list of available options will become available to you like so:
javascript autocomplete dot syntax

So now, we are moving our script out to it’s own file named, tut.js. Here is how we include it in the HTML:

Now that we have this in play, we can put some actual script in the script file just like this:

Excellent! Here we simply grab the element we are interested in, that would be the a tag, and assign it to a variable named a. Now we simply assign an anonymous function to the onclick event of that element. This anonymous function is the event handler which will only run when a user clicks the element. This is a much more common way to do things in JavaScript. If the idea of an anonymous function being assigned to an event or variable is new to you, don’t worry, we will be covering function in JavaScript in depth soon!

Add Event Listener

The third way to handle events is by using a special method which adds a listener to the document or element you are interested in. Let’s rewrite the prior example and use this style instead.

When we run the code by clicking our link, we can see some interesting things happen!
javascript addeventlistener

This brings us to a small discussion on the pros and cons of using this approach. As you noticed, we actually fired two actions based on the one click event. So this is quite a flexible thing. We can set up many listeners for just one event. It doesn’t necessarily have to be a click event either. With this added benefit though is also a drawback. The drawback here is that Internet Explorer version 8 and prior use a different method all together to accomplish this goal. Their method of doing this uses attachEvent('click', somefunc); This is easily solved by using a cross browser compatible library like jQuery for which there will also be a full series on soon 🙂


Common JavaScript Events

Now we’ll take a look at the most common events that you are bound to run across in day to day programming. Some of these include

onclick

The click event is one of the most common events to be used. Think about it, we navigate the entire internet based on clicks! It would make sense then for us to have a good grasp of how click events work in JavaScript. Let’s consider an example:

Upon loading this script up in the browser and clicking anywhere in the document, we see the logging correctly triggering. This is just a simple example to show that *any* element can handle the click event, not just a link, button, or image. The document is also an element, and by following the convention element.event we can do whatever we like in the page.
javascript document click

Clicking on the document is great, but it’s kind of like using a whale net to capture a minnow. In other words, it’s not all that useful. In real applications we’re going to need to respond to very specific click events. Since everything on the page is an element in the DOM, and accessing a JavaScript event follows the element.event convention, we can respond to a click on *anything* in the page. Let’s set up an example of clicking the Panda Image.

Loading this up in the browser and clicking the Panda gives us some strange results. If we click it, we’ll get the same exact response as the screenshot from the first example. Why is this not working? Notice in the HTML that we moved the script up into the head of the page rather than right before the closing body tag. Also remember that when websites load in a browser, everything is read from the top down and executed in the order in which it was read, including JavaScript. The problem in this example is that the JavaScript is executing before the Panda Image has even loaded on the page. It’s going to be hard to respond to a click on an element that does not yet exist! This leads to an important concept and rule to follow when dealing with JavaScript. It is important that all elements of the page have been loaded, which means that the DOM if fully in tact and in place, before any JavaScript executes. This is a common problem with a simple solution.

onload

The window object is the top level object in JavaScript. Even though we’ve been talking a lot about the document object, it is the window object that sits at the very pinnacle of the DOM. Because of this it is the window.onload event that tells us when the DOM has finished loading and is ready to go. We can make just a small modification to our JavaScript example, and everything will now work. Observe.

So what is going on here? We did not change the order in which the information gets read into the browser as the page loads. In fact, The browser is still hitting the JavaScript in question before the Panda Image loads. If we test this in the browser though, things are working.
javascript window onload event

The answer lies in the fact that we wrapped our existing JavaScript code within the window.onload event. Let’s talk it through. The web page begins loading and again comes across the JavaScript file first, before the Panda Image loads. Now, here is the difference: In the prior example, things started executing right as soon as the statements in the code were hit. Specifically, when this line of code tries to run

panda has a null value, so the code fails. In our new example, all of the JavaScript is inside the block:

When the JavaScript engine hits this line, it knows to read this as so. Do not execute any code inside this block until the webpage has been fully loaded. It is this line of code that tells us when the DOM is ready. In plain English, we can read it as, “When the web page is ready, execute this code”. And that is exactly what it does, and all is well!

onfocus and onblur

The onfocus and onblur events are used all the time in form processing. Let’s say we have an input field that is part of our webpage. We’d like users to be able to submit feedback about their thoughts on the Panda. It would be nice to add some interactivity to the input to prompt the user to enter some information, and clear the text when the user clicks in the field and is ready to type. Here is the markup and code to make that happen.

We can click in the input field and add our thoughts. When doing this, the default text will automatically clear.
javascript onblur onfocus event

Again, in talking it through, it will make all the sense in the world. The web page loads, and when the input field is encountered in the page, it is populated with the text, “Do you like the Panda? Click here to tell us!” This gives our users a good indication of what we would like them to do with this text input! Now, we have some JavaScript code that will run when the page is ready, as we did keep our logic inside of the window.onload event here. When this code runs, it checks to see when the user clicks inside of our input by making use of the onfocus event. onfocus tells us when a form field currently has focus, or when the user has clicked inside of it. When the user clicks this the field, focus is given, and at that time we check to see if the value of that element is equal to our default text. It is, so then, we instruct JavaScript to set this text to an empty string. This provides the action of clearing out our given text, and allows the user to type their own feedback. The next thing to happen is that we check to see if the user clicks away from this field using the onblur event. onblur tells us when the user has clicked somewhere else on the page, leaving the currently in focus element. The JavaScript then checks to see if the value of that element is an empty string. This condition would be true if the user clicked away and left a blank input. In that case, we want to remind them that hey, we want to know what you think about these Pandas friend. So what we will do, is that if the value is empty, we will re set that value right back to “Do you like the Panda? Click here to tell us!” This way, we are nudging the user in the right direction as to the call to action on the page. Pretty cool, right?!


JavaScript Timers

While not officially a JavaScript event, times are really incredible feature of the language. They do have a bit of an event-like feel to them, so why not cover what we can do with timers as well, right? Timers are used all the time for things like slideshows, clocks, or any other instance where we need an action to take place after a set period of time or several times over the course of time.

setTimeout

The setTimeout() function takes two arguments. The first is the function, or action to take. The second is the amount of time to wait before executing the given function. This value is provided in milliseconds. So for example, if we want something to happen after a 3 second time frame, we pass in 3000. We use setTimeout when we want an action to take place, but only after a specified time. Here is some example code to show setTimeout in action:

This is a pretty cool example, considering we could have simply just ran an alert to the page after 4 seconds 🙂 Instead, what we do here is populate 6 different div elements with a message. Each setTimeout event handles one part of the message, This is an example of Timers in JavaScript!

setInterval

The setInterval function is like a setTimeout on replay. If you have an action that you want to take place repeatedly at set intervals, you use this function. As always, we’ll provide a fun example:

javascript setinterval timer

Here is the idea of what is happening in this example. We have a very simple h1 element on the HTML page. The JavaScript is slightly more involved. Let’s bullet point it.

  • Fetch the element which had an id of message.
  • Populate a variable with an array of words.
  • Set an index to act as a counter.
  • Define a welike() function.
  • Populate the HTML element with an index of our array.
  • Move the index counter forward by 1.
  • Loop until all words in the array have been used.
  • If we reach the end of the array, reset the index counter to 0.
  • Use setInterval to call our welike function every 500 milliseconds.

When you load this in the Browser, you will witness an h1 tag which has text that changes between JavaScript, PHP, CSS, and HTML5 every 500 milliseconds.

clearInterval

Ok, you’ve set a bunch of words spinning about on the webpage every 500 milliseconds. Yes, it will not take long for this to start to drive you bananas. Before you scream, “Make it stop!” be comforted, we can write some JavaScript using the clearInterval function to bring your sanity back! Here is the updated HTML and JavaScript to give us a Start and Stop button to start and stop the welike() function in real time, it’s quite slick!

javascript clearinterval timer

How does clearInterval work? In this JavaScript snippet we do not simply make a call to setInterval passing in the welike function and 500 milliseconds. We first set up onclick event handlers for two new buttons on the HTML page. When the user clicks the Start Button, an anonymous function runs. Inside of the anonymous function is where we trigger that setInterval function. When clicked, this sets the welike function in motion once every 500 milliseconds. You’ll note that we also assigned a return value to the variable stopstart when setInterval was called. What this does is basically give us a handle into the setInterval process for this particular instance. We can pass this handle into the clearInterval function and it knows that this is instructing that instance of setInterval to stop. This is awesome stuff folks 🙂