We've mostly seen JavaScript's interactions with HTML as getting input from a form and writing output back to a text or textarea. But JavaScript can be closely integrated with every little aspect of a document, as the examples today will illustrate.
We've seen before how to control the value of text inputs and the value of check box inputs. We can go even further, and control the options presented in a select input. This again relies on the cross-referencing between JavaScript and HTML. Remember that a select is really just an array of options. We typically specify those options in the HTML, but JavaScript provides parallel functionality, so that we can specify them there.
document.selectName.options.length accesses the
length of the array of optionsdocument.selectName.options[index] accesses the
option at the indexnew Option("text") creates a new option that displays
the given text, just like <option>text</option>Examples:
JavaScript represents an image with another data type, called (appropriately enough) an "Image". Just like strings, numbers, etc., a variable can hold an Image, an Image can be passed to a function, etc. To create an image:
v = new Image(); v2 = new Image(width, height);
To set the source of the image, give a URL, just like with HTML:
v.src = "URL";
Cross-reference images in the HTML by their name, just like with a form.
document.imageName.src = "newurl"; // Changes the image source
There is also an array, document.images of all images
in the document.
document.images[0].src = "newurl"; // Changes the image source
We started integrating JavaScript with HTML via button clicks. A
button click is a type of event, or action by the user. We use
the onClick attribute for a button input, in order to specify
the JavaScript code that reacts to the event. We have seen some other
event handlers:
onClick: when the mouse button is pressed somewhere
(we saw with buttons, images, and radios; it's pretty generic)onMouseOver and onMouseOut: when the
mouse is moved over and element and out from it, respectively (we
saw with images, but again it's pretty generic.
onChange: when the selected option is changedThere are numerous other event handlers, and you can learn about them in a reference. Here are just a few other examples, to get you thinking about the diversity of event types to which JavaScript can respond. (In these examples, the JavaScript code is embedded right in the attribute, since it's simple enough not to require packaging in a separate function.)