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.
In this tutorial:
Required knowledge:
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:
- MozDevNet (no date) Functions – reusable blocks of code – Learn web development: MDN, MDN Web Docs. Available at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions (Accessed: 8 January 2024).
- MozDevNet (no date) Function return values – Learn web development: MDN, MDN Web Docs. Available at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values (Accessed: 8 January 2024).