Back back to styling a button

On the previous page we saw how to use styles to make a simple div element look like a button. Now we need to explore how to make it interactive.

Overview of Events

Put simply, an event is something that happens within the computer system that software can respond to. It could be the user clicking on something on screen, or pressing a key on the keyboard, or even inserting a DVD into the optical disk reader. In web programming we are usually concerned with the kind of events where the user interacts with an element in the page, such as moving the mouse into an element or clicking.

For our button example, there is only one event that we are interested in:

For more details, check out the W3Schools page for JavaScript events here.

The onclick Event

The onclick event is fired when a user clicks on something. If we have alerted the browser to our interest in that event, by registering an event handler, then we can make something happen when the user clicks.

Usually we will have an obvious style to indicate that something could be clicked on, but that isn't strictly necessary:

Click Me!

The code for the paragraph above is:

<p onclick="alert('You did it!')">Click Me!</p>

In this case, we have added an event handler for the onclick event directly to an ordinary paragraph of text. When the user clicks on the paragraph the built-in function alert will be called to display the message 'You did it!'.

A function is just a package of JavaScript code that will be performed when it is invoked. In this case some JavaScript, packaged under the name alert, is invoked when the user clicks on a paragraph. The message 'You did it!' is called the argument to the function - this means the message is passed to function as a piece of information for it to work with. in this case, it creates a pop-up window to display it.

There are a large number of predefined functions such as alert, but it is also possible to write our own functions for specific purposes. In order to get our button to work, we will have to write some functions of our own to attach to the required events. We will look at defining functions on the next page.

The onmouseover and onmouseout Events

Although we do not need them for this example, the onmouseover and onmouseout events are also useful.

The onmouseover event fires when the user moves the mouse over a particular element in the page. Similarly, the onmouseout event fires when the user moves the mouse out of a particular element on the page. Try moving the mouse in and out of the red square on the left.

This is done in exactly the same way as the onclick event handler except that the call to the alert function is attached to the onmouseover and onmouseout events and, obviously, the message given to the function is different in each case.

Functions in JavaScript... Next