Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Introduction to JavaScript event handling

From: JavaScript Essential Training

Video: 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.

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.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 101715 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.