Toggle Squares

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

Question:

Set up a table that looks like a chess board using red and black squares. When someone clicks on a square it should turn green and if they click on it again it should change back to its original colour.

Historical Answer:

Where I came across this question the students were not even allowed to use getElementById (or presumably any of the other DOM commands) and so a proper JavaScript solution was completely impossible. They would have needed to hard code the table into the HTML and attach an antiquated onclick event handler to each and every td tag to process the toggling of the colour in that square. Given the restriction on using DOM commands I am not sure how the teacher proposed that the JavaScript attached to the onclicks be written to handle changing the colour. Given the limitations this teacher gave, I am sure that any solution I attempted to write would make use of some feature of CSS or JavaScript that the teacher doesn't know exists or doesn't allow to be used and so I am not even going to try to write such an answer.

JavaScript Answer:

CSS
JavaScript

A few lines of CSS allow us to define the squares for the chess board and which squares are to have which colours and seven lines of JavaScript create the table without any inline event handlers. Also instead of needing 64 handlers to detect whether individual squares are clicked on we can simply attach one listener and then test where the click occurred to work out which square to change.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate