Step 3
The onclick event
-
When we click on the
zzzbutton we want something to happen! -
Update the
buttontag and add the followingonclickattribute:
<button onclick="window.alert('buzz!');">zzz</button>
HTML attributes provide additional information about HTML elements. They are always specified in the start tag, usually in name/value pairs like:
name="value".
- Save the
index.htmlfile; refresh theindexpage in the browser. Then, click on thezzzbutton. You must see a pop-up alert window sayingbuzz!
The
window.alert('buzz!');is a JavaScript statement. Thewindowobject represents an open window in a browser.
- Let's add another statement to
onclickevent of thezzzbutton.
<button onclick="window.alert('buzz!');console.log('fizz!');">
-
Save the
index.htmlfile; refresh theindexpage in the browser. -
In your browser, open "Developer Tools" (typically, you can do this by a right click and selecting "Inspect") and find the "Console" tab.
-
Now, click on the
zzzbutton. In addition to a pop-up alert window with the messagebuzz!, you must see the messagefizz!printed to the console.
console.log()provides access to the browser's debugging console.
The <script> tag
-
It will be difficult to read more than a few (JavaScript) statements for the
onclickattribute of thezzzbutton. It is not advisable to write event handlers (JavaScript statements that are executed in response to an event) using attributes of button (or other HTML) elements. The HTML document will soon become unwieldy. -
A better approach is putting all JavaScript statements (code) in a dedicated section, perhaps group the statements (pertaining to handling an event) in a function and call that function in the
onclickevent. -
Add the following section to the end of the
<body>element (right before the closing</body>tag):
<script>
function handleOnClickEvent() {
window.alert('buzz!');
console.log('fizz!');
}
</script>
The
<script>element is used to include JavaScript in HTML.
- Update the
onclickattribute of thezzzbutton:
<button onclick="handleOnClickEvent();">zzz</button>
- Save the
index.htmlfile; refresh theindexpage in the browser. Then, click on thezzzbutton; it must work as before (producing alert window and console message).