ptg16476052
Adding New Content to a Page 547
19
Exercise 19.3: Add an Expand All/Collapse All Link to the FAQ ▼
In this example, I’ll be adding a new feature to the FAQ page presented in the previous
example. In that example, I illustrated how to add new features to a page using JavaScript
without modifying the markup in any way. This example will continue along those lines.
In fact, I won’t be making any changes to the markup on the page; all the changes will
take place inside the JavaScript file.
In this example, I add a link to the page that expands all the questions in the FAQ, or, if
all the questions are already expanded, will collapse all the questions. The label on the
link will change depending on its behavior, and the function of the link will change if the
user individually collapses or expands all the questions.
Adding the Link to the Page Because the link only functions if the user has
JavaScript enabled, I am going to add it dynamically using JavaScript. I’ve added a new
function to the JavaScript file that takes care of adding the link, which I call from the
onload handler for the page. The function adds more than just a link to the page. It adds
a link, a
tion, which I’ve n amed addExpandAllLink():
function addExpandAllLink() {
var expandAllDiv, expandAllLink, faq;
expandAllDiv = document.createElement("div");
expandAllDiv.setAttribute("id", "expandAll");
expandAllLink = document.createElement("a");
expandAllLink.setAttribute("href", "#");
expandAllLink.setAttribute("id", "expandAllLink");
expandAllLink.appendChild(document.createTextNode("Expand All"));
expandAllDiv.appendChild(expandAllLink);
expandAllLink.onclick = function() {
var faqList, answers;
faqList = document.getElementById("faq");
answers = faqList.getElementsByTagName("dd");
if (this.innerHTML == "Expand All") {
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'block';
}
this.innerHTML = "Collapse All";
}
else {
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'none'; ▼