Triggering Events

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


Set up code so that when a button is clicked it adds 1 to the variable "numberofbeers"and then outputs the new total.

Historical Answer:

<button onclick="addBeers()">Add</button><div id="beers">0</div>
<script type="text/javascript">
var numberofbeers = 0;
function addBeers() {
document.getElementById('beers").innerHTML = ++numberofbeers;

Not quite as antiquated as some of the JavaScript questions being asked, this one at least expects that you are going to update something in the HTML in response to the event. We have even used a button tag because the "link" isn't intended to actually go anywhere. This solution does however suffer from having the HTML and JavaScript jumbled together with everything in the global namespace.

This old way of triggering events is no longer needed. At the very least you can move the event handler into the JavaScript (remembering that JavaScript is case sensitive and that event handlers should be specified in all lowercase). Better still is to abandon event handlers completely and use an event listener instead.

JavaScript Answer:

<button id="addBeers">add</button><div id="beers">0</div>
<script type="application/javascript">
(function() {
"use strict";
var addBeers, numberofbeers = 0;
addBeers = function() {
numberofbeers += 1;
document.getElementById('beers").textContent = numberofbeers;
document.getElementById('addBeers').addEventListener('click', addBeers, false);

This modernised alternative has separated the JavaScript out from the HTML and removed all of the JavaScript from the global namespace. It also uses a modern event listener in place of having an event handler hard coded in the HTML and is using the correct MIME type for the JavaScript in place of the antiquated one that used to be needed to support browsers that ran the now dead jScript language instead of JavaScript (so this script will not work in IE8 and earlier as they don't support JavaScript).

Note that we have also split out the content of the function into two separate statements to make the code more readable and less error prone. How many of you would have incorrectly used numberofbeers++ and incorrectly added one after updating the page instead of before?


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow