Advanced event handling
To handle events like mouse clicks and key presses in JavaScript, you attach event handling code to HTML elements. You can attach an event handling code in HTML, by adding an onevent attribute to an element; this code will be executed whenever that event happens.
In JavaScript, the most common events are onclick
, onkeypress
, onkeydown
,
and onkeyup
.
The special onload
event applies to the body
tag, and it runs after the page has finished loading.
It is also possible to add event handlers directly in JavaScript,
by accessing HTML elements and using onevent
fields:
Note that when event handlers are added in JavaScript, they are added functions rather than text.
That is, element.onclick = "alert('Alert me!');"
does not work.
When an event fires, the event handler function receives an event
object describing information about the event.
Browsers disagree on the naming of these fields, but for non-IE browsers,
the target
field contains the event which received the action:
Interacting with CSS
CSS is a means for separating the content of a web page from the
style of a web page.
JavaScript can interact with the CSS styles associated with each element
using the style
field.
In JavaScript, there are two ways to access a given style property--as
a literal field, or as a an index.
For example, one can render the following page:
by accessing all of the styles as fields:
or by accessing all of the styles as indexes:
Note that for CSS styles which contain hyphens, their name in JavaScript changes to
"camel case"; for example, background-color
becomes backgroundColor
.
Exercise: Minesweeper
Below, you'll find a partially constructed Minesweeper game.
The code creates the board with DOM tree manipulation, and stores
information about the game inside the DOM tree.
It randomly initializes the board with mines.
At the moment, it calls the procedure DisplayDebugInfo
when it starts, which overlays information on the board.
(If you want, have DisplayDebugInfo
invoked when the user
presses the character "C".)
You can decide on the precise controls, but it's recommend that a user should be able to highlight a cell, and click "F" to toggle the flag, or "B" to "clear" the cell.
For simplicity, you can use blue to mark a cell as flagged. If you're feeling adventurous, add some graphics!