Scripting a Simple Button

On this page I will show you how to create a simple button using styles and JavaScript. In the process we will learn about events. Before we look at how it's done, here's what we're going to build:

Click Me!

Roll the mouse over and out of the button, notice how the appearance changes. Try clicking on it to see what happens.

Defining Some Styles

As you probably expect, the appearance of the button is controlled by styles. Because there are two button states, normal and hovered, we have two different style definitions, one for each state.

Look at the two definitions side by side, the coloured highlighting shows the differences between the two rules:

.button {
    display: inline;
    padding: 5px 5px;
    text-decoration: none;
    border: 2px solid;
    border-radius: 6px;
    cursor: auto;
    background-color: #00CC00;
    color: #000;
    border-top-color: #AAFFAA;
    border-left-color: #AAFFAA;
    border-bottom-color: #006600;
    border-right-color: #006600;
}
.button:hover {





    cursor: pointer;
    background-color: #009900;
    color: #FFF;
    border-top-color: #006600;
    border-left-color: #006600;
    border-right-color: #AAFFAA;
    border-bottom-color: #AAFFAA;
}

The plain button rule always applies to the button element. The top half of the plain rule will also apply when the button is hovered because the hover rule does not contradict any of those properties. This is the part of the rule that defines the general display and shape parameters of the button. The hover rule differs where it specifies the colours of the different elements and where it defines what kind of cursor should be displayed.

Creating the Button

The button itself is simply a div (alternatively, you could use a span) with the approriate style applied. Consider the following piece of HTML:

<div id="button2" class="button">
    This is a Button!
</div>

Given the style rule defined above, this would produce an element in the page with the following appearance:

This is a Button!

But note this this only covers the visual appearance of the button, there is no interactivity! In order to interact with the button we need to understand events.

Events in web pages... Next