ptg16476052
540 LESSON 19: Using JavaScript in Your Pages
The page is designed so that it works perfectly well without JavaScript; all the ques-
tions and answers are displayed so that the user can read them. This is what unobtrusive
JavaScript is all about.
Adding the Script After the page has been created and you’ve confirmed that it’s
working correctly, the next step is to add JavaScript into the mix. To include the script on
the page, I just need to add the link to the external script to the header:
<script type="text/javascript" src="faq.js"></script>
That <script> tag loads and executes the script in the file faq.js. After the JavaScript
has been added, the answers to the questions are hidden, as shown i n Figure 19.7.
Here’s the JavaScript contained in the faq.js file:
window.onload = function() {
var faqList, answers, questionLinks, questions, curr entNode, i, j;
faqList = document.getElementById("faq");
answers = faqList.getElementsBy TagName("dd");
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'none';
}
questions = faqList.getElementsByTagName("dt");
for (i = 0; i < questions.length; i++) {
que stions[i].onclick = function() {
currentNode = this.nextSibling;
while (currentNode) {
if (currentNode.nodeType == "1" && currentNode.tagName == "DD") {
if (currentNode.style.display == 'none') {
FIGURE 19.7
The FAQ page with
the JavaScript
included.
▼
▼