Creating the toggle buttons (Building Interfaces) (iPhone JavaScript)

A toggle button allows you to choose between two possible states or values. The most common use of this widget is for actions or properties, whose value can be On or Off. The value can be changed by clicking on the button. It detects the event and automatically changes the value from one to the other.

Getting ready

As in the previous recipe, we’re following with the iUI framework for this recipe.

How to do it

Open the file you’ve created for the previous recipe with a text editor. We only use one row for the panel, so you can delete the other two rows. After the label tag for the one and only row, we’ll add the following code:

tmp1A81_thumb

Reload your modified HTML page for viewing the result, as shown in the next screenshot:

tmp1A82_thumb


Click on the button and observe how it changes to On. Observe that the color of the On state is blue, however the Off state is using a light gray color.

How it works

The main div element used by the toggle needs a special class called toggle. It can only be used inside rows for panels. Also, this HTML element requires three additional span tags and each one has its own CSS class. The first one belongs to the thumb class and is left blank. The toggleOn represents one of the possible values for the widget and the toggleOff the other value. Meanwhile, toggleOn will be the activated value and the toggleOff will be the disabled value.

The onclick JavaScript event handler manages the state for the toggle button. This handler can be used to respond to the event with a defined action using a JavaScript function. By default, the handler is using the return JavaScript command, which indicates that the button must change from On to Off and vice versa. This behavior is managed by the ui.js JavaScript file of the iUI framework.

Although the predetermined value for the toggle button is Off, you can change it by adding a no standard attribute for the div element. Specifically, this attribute is called toggled and its value should be true. The following segment of code shows you the modified div element:

tmp1A83_thumb

If you use the div element with the toggled attribute and reload your page, you’ll see how the toggle button is On instead of Off.

There’s more.

The toggle button is not exclusive to the iUI framework. Others such as iWebKit and PhoneGap allow you to create this kind of widget.

See also

► Installing the iUI framework recipe in topic 1, Frameworks Make Life Easier

Next post:

Previous post: