Lisa Wollin

JavaScript 101: Working with Events

It has been awhile since my last JavaScript 101 post. I apologize. I have a very lame excuse: I've been busy. But I'm back with the next installment: working with events.

Most JavaScript events are relatively simple and easy to use. For example, clicking on a button, an element, or a page. There are some more complex events that deal with data, but to keep this simple, I'll talk only about the ones that affect user interaction, such as onclick, onmouseover, onmouseout, and onfocus. There are, of course, many more events than this, but these four events seem to cover a majority of the uses that you will need ... at least to start with.

The Script

First, of course, you need a script, so here's a simple little script.  All it does is display a message box.  Just copy the code below, including the opening and closing <script> tags, and paste them into the HEAD section of a Web page.

<script language="javascript">
function ShowMessage(text)
{
    window.alert(text);
}
</script>

In order to call a script from an event, it must be inside a function, so the above script contains a function called "ShowMessage" that takes one argument, the text to be displayed.

Note   As I mentioned in my last JavaScript 101 post, you can use IntelliSense in Code view in FrontPage to write your scripts.

The HTML

Second, you need to reference the function from an event inside of an element. I'll use a P element. Here's the HTML code that you need.

<p>Here is a sample paragraph 
with an event.</p>

Putting Them Both Together

Next, add to the P element a an event handler that calls the function.  You can add it to any event, such as the onload event, but to make things simple, add it to the onclick event.  Here's the code:

onclick="ShowMessage
('A little JavaScript fun!');"

Your P element should now look like the following code:

<p oncl­ick="ShowMessage
('A little JavaScript fun!');">
Here is a sample paragraph with 
an event.</p>

And that's it.  Save your page and display it in the browser.  When you click on the text in the paragraph, the browser displays a message like the one in the following image.

What You've Learned

In this post you learned how to hook up a JavaScript function with an event handler for an HTML element. Now that you understand how to hook your scripts up to events to create user interaction, we can move onto writing more scripts.  Next time, I'll talk about working with text—things like changing the text or HTML in an element, changing colors, formatting, etc. Until then, have fun!

Published Wednesday, July 13, 2005 3:50 PM by lisawoll
Filed under:
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker