Buttons are normally seen on web pages as part of forms - for example a submit button for sending user details to the server; however buttons can actually be used at any time and for any purpose - by making uses of the Javascript onclick event.
The Javascript onclick event is triggered whenever the web page user clicks on a button (or any other object, for that matter) - it's then just a matter of associating some code with the event.
Assigning a Function to the Javascript Onclick Event
A function can be assigned to the onclick event for a button when the button is defined in HTML, for example:
In this example the button_1_onclick will be run when the button is clicked and, of course, the function will need to be defined as well:
In this example the code is specific to the button, however, it is possible to write a generic subroutine that can be assigned to more that one button.
Onclick Events for Multiple Buttons
Every button that is defined in the HTML will have it's own onclick event, but rather than write individual subroutines it may be more efficient for the programmer to write a single subroutine to be processed by any button added:
In this case the onclick event is not defined in the HTML, it's set in the code:
Now a single subroutine can be created for both buttons:
The subroutine simply updates a div area with the id of the button that the user has clicked - and for that a second subroutine is required - one to obtain the id of the button.
Obtaining an Object's ID
The method for obtaining an object's varies according to the type of browser being used:
The advantage creating a function to obtain the object's id is that it can be used elsewhere in the Javascript code.
Handling All Clicks on the Document
Rather than handling the clicks from individual buttons it is possible to handle anyclick that the user performs - and that's done by working with the document's onclick event:
In this way the programmer can control any clicks that the user carried out.
Summary
If a user clicks on a web page then the Javascript onclick event is triggered - the onclick event can be associated with individual objects (such as buttons) or by any object on the web page (for example buttons, div areas and the body). Subroutines can then be associated with the onclick events to give the programmer full control of all of the user activities on the web page.