Step 4

The onclick event

  • When we click on the zzz button we want something to happen!

  • Update the button tag and add the following onclick 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 the index page in the browser. Then, click on the zzz button. You must see a pop-up alert window saying buzz!

The window.alert('buzz!'); is a JavaScript statement. The window object represents an open window in a browser.

  • Let's add another statement to onclick event of the zzz button.
<button onclick="window.alert('buzz!');console.log('fizz!');">
  • Save the index.html file; refresh the index 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 message buzz!, you must see the message fizz! 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 the zzz 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 the zzz button:
<button onclick="handleOnClickEvent();">zzz</button>
  • Save the index.html file; refresh the index page in the browser. Then, click on the zzz button; it must work as before (producing alert window and console message).