Watching:

JavaScript Essential Training: Handle and Recognize Events


show more Find out how to react to user input and system events with JavaScript event handling. Learn to recognize events (onclick, onfocus, etc.) and write event listeners and event handlers that react to those events and perform another action when triggered, such as running a function. Plus, find out about the benefits and drawbacks of writing your own code with addEventListener and attachEvent and why you might want to use a free third-party JavaScript library such as jQuery. show less
please wait ...

Introduction to JavaScript event handling

So we're starting to write some deeper code, but it's still happening as soon as the browser gets to it. And that's not a very interactive situation. We're not reacting to anything the user is doing yet. We can fix that by working with events. Maybe I've got some JavaScript that I only want to run when a link is clicked on the page. Or if the user tries to submit a form, I want to make sure that they've filled out the form first. And I want to make sure that not only has the page loaded, but also all of the assets it's linking to, including images and style sheets and so on.

And we can do all of these things and a lot more with events. Now here's the thing with events. It's common for someone new to JavaScript or new to programming to get a little puzzled about your role here. You're thinking, "Am I supposed to write the event? How do you describe an event?" Well, you don't, because here's the deal. The events are already happening. They've been happening all along. When the page is loaded, that's an event; when the user clicks a button, that's another event; when they move their mouse, that's a whole bunch of events; when they scroll the screen, that's an event; when they click a form field, that's an event; as they type, every key press is another event.

Events are going on all the time. You have to decide which ones you care about. See, these events are built into JavaScript. They're part of JavaScript, and there are special words to describe them. You'll see them typically written all lowercase, and they begin with the word on, so onload, onclick, onmouseover, onblur, onfocus, and we'll see several of these in the next couple of movies. But you don't write the event itself. You write what's called the event handler or the event listener, whatever term you prefer.

You write your function and you volunteer to handle or to listen out for one or more events, so that you can respond when they happen. And I'm going to talk about and cover three ways you can react to an event in JavaScript. One is the simplest and the ugliest way. You can just write JavaScript code directly in your HTML, so if you have a button tag in your HTML, you can use that word onclick-- again, this is the event--onclick = and in this case I'm just directly typing in JavaScript, the alert('Hello, world') here.

I'm not a fan of this method, for multiple reasons. It's going back to having script mixed in with our HTML, which I'd like to avoid as much as I like to avoid CSS mixed in with our HTML. While you can include multiple statements here separated by semicolons, really, how much do you want to write like this? And if we did this a lot, we wouldn't be reusing code like we can with an external file, and there's no way to make this friendly if JavaScript is disabled. But you will see it from time to time. The second way is to use the name of the element, then a dot, then the name of the event.

So window.onload means the onload event of the window object; nameField.onblur means the onblur event of the nameField object; or quite classically, just myelement.onclick. When they click a DOM element, we want to do something, so we use the equal sign and then this following format: the word function(), and then the opening and closing curly braces, and then you put your event handler code inside here, whatever you want to execute when they click that element, whether that's one line or a hundred.

And what we're doing here is what's called an anonymous function. This is very, very common in JavaScript, and you'll see it all over the place. It might look a little weird because usually we use the word function and we give our function a name, but we're not doing that here. And that's okay. Think about the reason for a function. We usually use a function to wrap up a bunch of code and give it a name so we can call it later. Well, here, we're still using the word function to wrap up a bunch of code-- whatever is in between the opening and closing curly braces--but we don't have to give it a name because we're saying exactly when this gets executed, which is when they click myelement.

So when this event happens, we want to run this function, whatever is in this block of code, so naming it would be a waste of time. Now one important thing here, bear in mind, if you write this code, the first time JavaScript reads it, it won't actually do anything with the function. What you're actually saying is later on when the user clicks this element, we execute this code. I'm just telling you about it right now. And because of that, there's a little addition to this that often messes people up when they first see it, which is we're ending this all with the semicolon.

And it's very common for beginners to JavaScript to look at this and go, "I don't quite understand. I didn't think we used semicolons around functions." And people get very puzzled because they think, "When do I need a semicolon. Do I put it at the end of a function or don't I put it at the end of a function?" Well, the thing about it is this: it's nothing to do with the function. We're not putting the semicolon there because this is a function; we're putting the semicolon there because the whole thing is a statement. We're saying myelement.onclick = this function.

That's why the semicolon goes at the end of the block here. The same way I put a semicolon at the end of var a = 5, I put it at the end of myelement.onclick = function(). In most cases, it would work if you forgot the semicolon, but you will see this format a lot. And then there's the third method of deciding to handle or register for an event. This has one huge benefit and one huge drawback. It's using a method called addEventListener, which you can either call directly on the document object or on any element that you have.

And you give it three pieces of information: the event--and here you actually write it without the word on, so click rather than onclick, mouseover rather than onmouseover-- then a comma, then the function you want to run, and then the term false. We're actually interested in the first two arguments here. What event are we listening for and what function gets called when it happens? This third false argument is an option for some super-advanced event handling that's very unusual to need. Now the big benefit is using this way you can actually add a listener to multiple events. You can add one event and have multiple listeners.

You have a lot of flexibility to dynamically add and use its mirror image to remove event listeners as your script is running. If that's the big benefit, here's the big problem. This is one of the very few areas left where there is still a difference between the browsers. Because Internet Explorer, prior to IE 9, does not have the addEventListener function. It has its equivalent which is the attachEvent method, which takes two parameters. Same idea; it's the event name itself and then the function.

It's the same concept, but it's a different name. And that's a small difference that makes a big difference because to use this we now need to write code to detect whether or not these functions exist. And if I wanted to be agnostic about the browser, what I'd probably typically do is write my own little helper method. I'd write my own function called say addCrossBrowserEventListener, and I could pass it information. And it would do a little bit of scanning to see, does the EventListener function exist? If it does, we'll use the addEventListener function; if it doesn't, we'll use the attachEvent one.

Now here's the thing. I have written a lot of cross-browser detection code in my time, but these days I do my best to avoid ever handwriting functions that deal with cross-browser issues. If I need the benefits of addEventListener and attachEvent, I will not write my own code to handle the difference. I'll use one of the free third-party JavaScript libraries like jQuery. A big part of what they do is provide excellent cross-browser functions for situations like this. We'll talk about these libraries a little later.

Because of this reason, in this course I'm going to be using the simpler, more straightforward, but cross-browser compatible methods of creating event handlers.

Introduction to JavaScript event handling
Video duration: 8m 16s 5h 31m Beginner

Viewers:

Find out how to react to user input and system events with JavaScript event handling. Learn to recognize events (onclick, onfocus, etc.) and write event listeners and event handlers that react to those events and perform another action when triggered, such as running a function. Plus, find out about the benefits and drawbacks of writing your own code with addEventListener and attachEvent and why you might want to use a free third-party JavaScript library such as jQuery.

Subjects:
Developer Web
Software:
JavaScript
Author:
please wait ...