Mike: Are there any ru le s such as where to p ut a <script > ele ment referring to
JavaScript code that will execute asynchronously?
Professor: There is a general agreement that you place it inside the head of the doc-
ument. You’ll also come across the advice that <script > elements should be placed
after any <link> elements that refer to external CSS. That is, however, irrelevant for
JavaScript that is executed asynchronously because the style information will already
have been available at the time of JavaScript code execution no matter where the ac-
tual code is include d. Tha t’s because styles are needed if the page is to be rendered
correctly.
Mike: Why is tha t impor ta nt? I mean what ha s Java Script to do with CSS?
Professor: You will soon learn that you can manipulate styles dynamically using
JavaScript, which is called style scripting. If you want to manipulate styles, it is
important that they are available, of course. Tha t’s why CSS should be loaded before
JavaScript executes. But more on this later.
12.4 Scripting Documents
Professor: The mo st fundam ental role of client-side JavaScript is to make static
HTML documents responsive to user and other ac tions and turn them into either dy-
namic documents or web applications.
If yo u use JavaScript in web documents only to a ugment HTML with behavior, then
you get what is usua lly called Dyna m ic HTML or DHTML. In such cases, JavaScript
should only be used to enhance a visitor’s browsing experience. The actual content
that a visitor can read, however, should by no means be dependent on JavaScript.
On the other hand, if you go beyond tha t limitation of merely enhan cing a visitor’s
experience, you get what is called a web application. The HTML5 specification de-
fines a whole lot of objects that allow yo u to perform application-like feats such a s
manipulating graphics or storing and retrieving data. Such sets of objects are called
application programming inte rfa ces or APIs because programmers use them for inter-
acting with dierent (software and hardware) components. There’s simply too much
of everything, so we’re not going to plunge into details. I’ll just leave you so me clues
at the end of this course as to which directions you can take. They are gather ed in
Appendix B of this book.
It doesn’t matter whether you’re up to developing dynamic doc uments or web appli-
cations—there’s o ne API you w ill constantly work with. It is called the Document
Object Model API, or DOM API. Think of DOM as being an object representation of
the collection of all the HTML elements and strings of text positioned on a web pag e.
By usin g DOM API, the programmer can manipulate or query any ele ment or string
of text on a web page indirectly by manipulating or querying a corre sponding DOM
object.
The fundamenta l object of th e DOM API is the Document object, which represents
whatever is displayed in the browser’s window. Th e Document object is a property
of the Window object and can hence b e accessed a s a global property under the n ame
12.4. Scripting Document s 233
document.
Maria: Has this got anything to do with the document.write() that we’ve been
using?
Professor: Ind eed it has. Weve been using the Do cument’s write() method in ord er
to write text to the document, w hich we are no longer going to do. Instead, we’re going
to use Documen t’s other methods and proper ties in order to work with its content.
One of the more important methods of the D ocument object is getElementById(),
which returns a reference to an Element object that represents a specific HTML ele-
ment. The method makes use of th e id HTML attribute to identify the HTML element
you want to fetch. Because the value of the elemen t’s ID must be uniqu e within the
document, yo u’ll always know exactly which element you have got a reference to .
Don’t panic, here comes an example. Imagine you have the following line of HTML
code so mewhere in your doc ument:
<div id="click-me">Click me, please.</div>
If yo u pass the value o f the id attribute as an argument to getElementById(), you
get a reference to the Element object representing the above <div> element:
var myDiv = document.getElementById("click-me");
The following pictu re shows how a DOM E le ment object gives JavaScript access to
dierent parts of an HTML element through its corresponding properties.
HTML
JavaScript
<div id="click-me">Click me, please.</div>
var myDiv = document.getElementById("click-me");
DOM Element object
tagName
id
innerHTML
"DIV"
"click-me"
"Click me, please."
myDiv.innerHTML = "Thanks!";
Property
Value
console.log(myDiv.tagName); //Writes DIV
The most important property is of course id, which allows the getElementById()
method to return a reference to the correct Element object. In th e above example, a
referenc e to the Element object representing <div > is stored in the myDiv variable.
Once you have obtained this refere nce, you can either set or query the Element ob-
ject’s prope rties in the usual way, thus indirectly manipulating the u nderlying HTML
234 Meeting 12. Using JavaScript to Control the Browser
element. For examp le , in the last line of JavaScript code in the above picture, the value
of the tagName property is written to the JavaScript Console.
If you browse through the properties of the the Element class in the JavaScript ref-
erence, you’ll find the innerHTML property on page 399. This property r epresents
whatever is p la ced between the opening and closing tags of the element, and you can
read as well as set this prop erty. If you set the i nnerHTML property to a new string, the
parsed representation of this new string will be shown in the br owser window instead
of whatever has been inside the elem ent b efore that. In the above pictur e, the second
line of the JavaScript code changes the text that is displayed on a page from “Click
me, please. to “Thanks!”
Of course, it d oesn’t make much sense to immediate ly ch ange the value of innerHTML.
Instead, we can allow our visitor to change the text from “Click me, please. to
“Thanks!” by clicking the <div> element. For this purpose we simply define the
onclick event handler on the myDiv Element object.
One question that ne eds to be answered before we do this is how you can r efer to the
Element object from within the event-hand le r function definition. Any idea?
Maria: It seems very similar to an ordinary method de finition to me. If an event-
handler function is invoked as a metho d of a specific Element object, then this object
acts as the invocation context of the handler and we can probably use this to access
it.
Here’s the complete o nclick event-handler definition:
myDiv.onclick = function() {
this.innerHTML = "Thanks!";
};
Professor: Splendid! And don’t forget to put all the JavaScript code for this last
example inside the onload event handler.
Incidenta lly, in this particular case you could just as well use myDiv instead of this
inside the function definition, bec ause the function is u sed on a sin gle object instance.
This is, however, not possible as soon as you want to use the same function definition
on more than one object instance. Consider, for example, that you have two Element
objects, obj1 and obj2, and you want to thank each one of them individually. This is
what you could do:
var thankYou = function() {
this.innerHTML = "Thanks!";
};
obj1.onclick = thankYou;
obj2.onclick = thankYou;
In this case this is the only possible solution.
12.4. Scripting Document s 235
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.44.223