JavaScript Placement: Event Handlers
JavaScript is bound to individual HTML documents by placing it in
source files and within
script tags, but it can also be placed directly in an HTML tag using
event handlers.
Event handlers are HTML tag attributes which refer to a specific action which takes place within the context of a browser window. They are used to delay execution of JavaScript until a certain action takes place. One example of this is
image rollovers, where an image changes when the mouse pointer moves over it. Event handlers are why JavaScript is able to interact with the end user.
A few popular event handlers are: onMouseOver, onMouseOut, onLoad, onSubmit and onClick. To see more, check out
Netscape Devedge's list of event handlers.
Like any other HTML tag attribute, event handlers belong inside an HTML tag, are followed by an equals sign and their values are quoted. The difference is that the event handler's value is JavaScript.
onMouseOver="document.socks.src='shoes.gif'"
Quotes, Nested Quotes and Event Handlers
Notice the use of the double quotes around the event handler's statement, and the single quotes around part of the statement above. All JavaScript code within an event handler must be contained in double quotes. The JavaScript engine executes statements starting with an event handler's first double quote, and ending with the very next double quote it encounters.
As in the example above, sometimes a piece of a line of JavaScript must be quoted. Because of this, any such JavaScript code within an event handler that requires quoting must use single quotes. In other words,
quote nesting is required. Watch this - a very common mistake new scripters make is improperly nesting quotes.
You will learn which parts of JavaScript should be quoted as you learn more about the language. For now, all you need to know is that certain types of
values, known as
strings, are stored within quotes.
>>
Objects, Properties and Methods
>>
The Dot Syntax
>>
Dot Syntax Alternatives
>>
JavaScript Statements
>>
JavaScript Placement: Script Tags and Source Files
>>JavaScript Placement: Event Handlers