In the Hello World! Javascript primer our JavaScript ran as soon as the script loaded in the browser. JavaScript is event-driven: scripts run when a specific HTML event occurs in an HTML document. In the Hello World! example, the event is the loading of the page.

1. Basic

The basic HTML code below includes code that should run when something is clicked. In this example, the onclick() event is attached to the image element. The code that should run is a simple Javascript alert();

<html>
<head>
	<title>Javascript's onclick event</title>
</head>
<body>

<h1>The onclick Event</h1>
<img src="sicon_mini.gif" id="pageLogo" alt="The stylus logo."  onclick="alert('You clicked, Lord Master?');" />

</body>
</html>

2. Refactor: create a function

It is preferable to separate your JavaScript code from your HTML. It is also always preferable to put your code in functions that can be called from different places.

The above code can be refactored as follows:

<html>
<head>
	<title>Javascript's onclick event</title>
</head>
<body>

<h1>The onclick Event</h1>
<img src="sicon_mini.gif" id="pageLogo" alt="The stylus logo." onclick="myFunction();" />

<script>
function myFunction() {
	alert("You clicked, Lord Master?");
}
</script>

</body>
</html>

3. Advantage

Creating a function has the advantage that you can now call that function from anywhere on the page. It can also be called from more than one place.

<html>
<head>
	<title>Javascript's onclick event</title>
</head>
<body>

<h1 onclick="myFunction();">The onclick Event</h1>
<img src="sicon_mini.gif" id="pageLogo" alt="The stylus logo." onclick="myFunction();" />

<script>
function myFunction() {
	alert("You clicked, Lord Master?");
}
</script>

</body>
</html>

4. Codepen

See the Pen Javascript’s onclick() event by David Fox (@foxbeefly) on CodePen.

5. Next steps

In step 2 of this tutorial, we wrote and called a function. In the next tutorial, JavaScript’s onmouseover() event, we take this one step further and create a separate JavaScript file for our JavaScript code.

You may also want to take a look at the JavaScript’s addEventListener() method tutorial.


References:

  1. MozDevNet (no date) Functions – reusable blocks of code – Learn web development: MDNMDN Web Docs. Available at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions (Accessed: 8 January 2024).
  2. MozDevNet (no date) Function return values – Learn web development: MDNMDN Web Docs. Available at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values (Accessed: 8 January 2024).

By MisterFoxOnline

Mister Fox AKA @MisterFoxOnline is an ICT, IT and CAT Teacher who has just finished training as a Young Engineers instructor. He has a passion for technology and loves to find solutions to problems using the skills he has learned in the course of his IT career.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.