kirupa.com - JavaScript Events 


Active Discussions

JavaScript Events

by kirupa   |   28 April 2011

  Have questions? Discuss this HTML5 tutorial with others on the forums.

In the grand scheme of things, applications are pretty boring when left alone:

this is a boring application

[ yaaaawn! ]

Most of them just sit there - providing nothing of value to society. Things change when you start interacting with them though. The lifeless beings suddenly start reacting to the various mouse clicks, keyboard presses, and other things that you may do.

Similar to how nerves in your body help send messages throughout, the magical force that enables your applications to react is known as events. Almost always when you or your application does something, an event is fired. If you have some code to listen for that event, you can make your application do stuff. Let's look at an example.

Click on the image below to see a very simple example of events in action:

click example

[ click on the image to launch a new page containing the example ]

When you launch the page and click on the click me button, a dialog will appear that looks as follows:

this dialog shows me what I am clicking

While this example may not be the most fancy one you may have seen, it does a good job setting up the stage for what you will be learning.

Meeting Events
Similar to peeling an onion, let's look at events in layers. There are two parts to the sequence of actions that led to the dialog appearing:

  1. You clicking on the button
  2. The button reacting to the click by displaying the dialog

When you clicked on the button, your browser fired what is known as an event letting everyone know that your button was clicked. Somewhere in your application, you had some code that was listening for this event. When this event was fired by the browser, your code listening for that event executed, and this resulted in the dialog getting displayed.

Ok, let's dive a bit deeper and put the previous paragraph into code. If you haven't done so already, visit the example page and view the source. From your source, you will see a fair amount of CSS and HTML and some JS code to just get the visuals up and running. From all of this, the most relevant lines are what I've pasted below:

clickButton.addEventListener('click', displayDialog, false);
  
function displayDialog(e) {
window.alert("you clicked me!");
}

These lines correspond to listening for the event and reacting to it by displaying a dialog when the event is overheard. Don't worry if you don't fully understand what these lines of code actually mean. I'll explain how they fit shortly.

Listening for Events

The first thing we are going to do is learn how to listen to events that get fired. This is where things get exciting and fun. Like I mentioned earlier, almost everything you do results in an event getting triggered. Sometimes, your application will fire events automatically such as when it loads. Sometimes your application will fire events as a reaction to you actually interacting with it. Needless to say, your application is bombarded by events constantly whether you intended to have them get fired or not. The trick is to listen to the right events and react as needed.

The thankless job of listening to the right event is handled entirely by a function called addEventListener. This function is responsible for being eternally vigilant so that it can notify another part of your application when an interested event gets fired:

source.addEventListener(eventName, eventHandler, false);

You use the addEventListener function by first specifying which element you want to listen to events on. In our case, that will be the button which we will call clickButton:

clickButton.addEventListener(eventName, eventHandler, false);

Once you know which element you want to listen for events on, the next step is to actually specify the event you want to listen for. We want to listen to the event associated with clicking, and in JavaScript, that is the click event:

clickButton.addEventListener('click', eventHandler, false);

The final thing we will do is specify the name of the function that will get called when this event does get fired. Let’s call this function displayDialog:

clickButton.addEventListener('click', displayDialog, false);

The final thing we are going to cover is the last argument relates to event capturing. I couldn't do a better job explaining this than what Peter-Paul Koch of quirksmode has done, so go there to learn all about it. (Thanks to actionAction for the heads-up!)

All right! Your event listener declaration is now complete. It is now ready to listen to the mousedown event on your button and calling the displayDialog function when it hears the mousedown event.

The Event Handler

The function that gets called when an event you are listening for gets fired is known as the event handler. In our example, as you saw from the addEventListener call earlier, the event handler is called displayDialog, and the function looks as follows:

function displayDialog(e) {
window.alert("you clicked me!");
}

Notice that the function declaration is pretty much the same as any other function that you would declare. The only variation is that the function takes a single argument known as the event arguments or eventargs for short. We’ll look at event arguments in more detail in a future tutorial, so just know that they exist but don’t worry about them for now.

The only other thing to know is that any code that you want to execute when your event is fired will live here. For our example, the actual code inside our displayDialog function is pretty straightforward. It is just a simple window.alert call.

Conclusion

Well, that's all there is to getting an introduction to events. You have your addEventListener function that allows you to register an event handler function that will get called when an event gets fired. When that event gets fired, any code inside your event handler executes and your application is said to have reacted to the event having been fired.

Need Help?

If you have questions, need some assistance on this topic, or just want to chat - please drop by our friendly forums and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out. Plus, we have a large collection of smileys you can use

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly at kirupa[at]kirupa.com.

Cheers!

Kirupa Chinnathambi
about | facebook | twitter


cloud storage
                          EdgeCast CDN
kirupa.com's fast and reliable hosting provided by Media Temple. Creative web apps. Make your own free flash banners and photo slideshows.
HTML5 CSS3 Mobile Gallery for iPhone, iPad Flash effects. Art without coding.
Flipping Book - page flip flash component. Flash-Gallery.com - Get your flash photo gallery (flash component or swf gallery
Learn how to advertise on kirupa.com