Step 4
The onclick
event
-
When we click on the
zzz
button we want something to happen! -
Update the
button
tag and add the followingonclick
attribute:
<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.html
file; refresh theindex
page in the browser. Then, click on thezzz
button. You must see a pop-up alert window sayingbuzz!
The
window.alert('buzz!');
is a JavaScript statement. Thewindow
object represents an open window in a browser.
- Let's add another statement to
onclick
event of thezzz
button.
<button onclick="window.alert('buzz!');console.log('fizz!');">
-
Save the
index.html
file; refresh theindex
page 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
zzz
button. 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
onclick
attribute of thezzz
button. 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
onclick
event. -
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
onclick
attribute of thezzz
button:
<button onclick="handleOnClickEvent();">zzz</button>
- Save the
index.html
file; refresh theindex
page in the browser. Then, click on thezzz
button; it must work as before (producing alert window and console message).