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

Working with onClick and onLoad events

From: JavaScript Essential Training

Video: Working with onClick and onLoad events

So now I'm going to write some code to respond to common events, and if there are two events in any programming language that are the most common, it's clicking on something and loading something. So I have a regular HTML page here with some images and CSS linking to a JavaScript file that's actually currently empty, and I have both of those just open in my editor here. So the simplest way that I could cause something to happen is like I have on Line 28 here where I just have the onclick = inline code in my HTML itself, and no particular surprise on what this is going to do. If I click that button, I'll run that alert message.

Working with onClick and onLoad events

So now I'm going to write some code to respond to common events, and if there are two events in any programming language that are the most common, it's clicking on something and loading something. So I have a regular HTML page here with some images and CSS linking to a JavaScript file that's actually currently empty, and I have both of those just open in my editor here. So the simplest way that I could cause something to happen is like I have on Line 28 here where I just have the onclick = inline code in my HTML itself, and no particular surprise on what this is going to do. If I click that button, I'll run that alert message.

But we are not going to do any more code like this. We are going to do it properly. So I am going to jump across into my script.js, which is already being linked to, but there's no script in it yet. Now it's easy to think that we need a button or a link to click on. We can support the idea of clicking on anything in our document. Click is a very generic event. And we mentioned that we need to write element.event, so what's an element? Well, one of the top-level ones I have here is document. The document is an element itself. document., and event name, I'll say onclick =, and this is where we then write what's called the anonymous function.

This isn't the only way of doing it here, but this is the most common way. So the word function, opening and closing parentheses, and opening and closing curly braces that contain whatever code I want to execute. In this case, I am going to do something simple, alert ("You clicked somewhere in the document"). So I jump over to the browser, I reload the page, and as soon as I clicked, I should get that alert message. The only thing I have to be careful with would be clicking on perhaps one of these links, which actually won't go anywhere right now and get a missing page.

But you can see I don't have to click explicitly on a button; it can react to it anywhere. Now it's probably not all that useful to make the entire document respond to clicking. So what we could do instead, I am going to jump over and do a slightly different one here. First, I'm going to create a variable.

First, I am going to create a variable and just grab hold of an image which has the ID of main image, because if I want to respond to an event, I don't have to respond at the document level. I don't have to say document.onclick. I can use any element.onclick. So now I got that image, I could say myImage.onclick = another anonymous function, and we'll pop up in the message, You clicked the image.

Save that, jump back over into the browser, and refresh this page. Now if I click the image, I should get the message, "You've clicked the image," though having said that, this is also considered a document click, so I'll get that other event as well. If I click somewhere off the image, I'll just get "You've clicked somewhere in the document," but it can also target the image, which again, has the document as well. So you can target this event handling at any level that you want to.

You don't have to have a button or a link to click on. It can be any element on the page. Up to this point, what I've done is I've recommended always putting any links to external JavaScript files right here at the end before the closing body tag, and that is a good rule. However, it doesn't guarantee that your page and all its assets are loaded. If you're loading CSS files, images, et cetera, you might actually hit and run your JavaScript before everything has been fetched from the server. So it's very common to make sure everything is loaded before we start running any JavaScript at all.

I am going to emulate this by just doing a little trick here. I am going to grab the script tag and just put it up here somewhere in the head of the document. So it's going to be loaded as soon as the browser sees Line 7, before it even gets onto the body here. I am going to jump over into script.js. I am just going to remove that document.onclick function, because I don't really need it here. I just want one responding. So still I have that code to say when you click the image pop up an alert box.

I jump over to the browser. I am going to reload this page. Now if I click this image, I don't have anything, because the problem here is that the browser is trying to execute this JavaScript as soon as it gets to it. It's trying to grab this element called mainImage, but it's trying to run that around about here, before it passes the rest of the page. It doesn't have an element called mainImage. So it can't add itself to onclick.

So how do we deal with this? Well, this is a very, very common issue, and the event we want to respond to is the onload event of the window object, not the clickevent of the myImage object or the mouseover event of the document, but window.onload. Now we haven't really touched on the window object very much. We've been staying focused on the document object. The window actually represents a full browser window. It is actually the top-level object in JavaScript. It contains the document object.

And it's this that can tell us when everything is loaded. I use the same format, the.event format here, and I'll just do an anonymous function. So call any other functions, "prep anything we need to." In fact, a good idea here is that what I might do is create a new named function. Let's imagine that we had multiple event handlers that we were worried about.

So I am going to grab my code and paste it in there, so that when this function is called, it will try and add an event handler to the image, but I am going to make sure that function doesn't get called until the document has completely loaded. Save that jump, back over into the browser, and now, even though the JavaScript is loading immediately, we should get our successful event handlers popping up here, because the browser is reading the code.

It's understanding the function and then it's hitting this window.onload and realizing, okay, I'm only going to call Line 18 after the document has fully loaded, regardless of where the script was placed in the HTML. Now as we get more complex, one thing to watch out for is that you should only write this window.onload function once per page, and if you ever link to multiple JavaScript files and find out that you've got multiple files trying to do the same thing, it's only the last one that's going to win. But window.onload is a very common event and one you are going to react to a lot.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 112598 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 preferences from 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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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.