Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

550 LESSON 19: Using JavaScript in Your Pages


faqList = document.getElementById("faq");
answers = faqList.getElementsByTagName("dd");
expandAllLink = document.getElementById("expandAllLink");
switchLink = true;

if (expandAllLink.innerHTML == "Expand All") {
for (i = 0; i < answers.length; i++) {
if (answers[i].style.display == 'none') {
switchLink = false;
}
}

if (switchLink) {
expandAllLink.innerHTML = "Collapse All";
}
}
else {
for (i = 0; i < answers.length; i++) {
if (answers[i].style.display == 'block') {
switchLink = false;
}
}

if (switchLink) {
expandAllLink.innerHTML = "Expand All";
}
}
}

This function starts with some setup. I declare the variables I will be using and retrieve
the elements I need to access from the DOM. I also set the variable switchLink to true.
This variable is used to track whether I need to switch the link text in the Expand All
link. Once everything is set up, I use an if statement to test the state of the link. If the
link text is set to Expand All, it checks each of the answers. If any of them are hidden,
it leaves the link as is. If all of them are displayed, it changes the link text to Collapse
All. If the link text is already Collapse All, the test is the opposite. It switches the link
text to Expand All if all the questions are hidden.
Now let’s look at how I could accomplish the same thing using jQuery. Inside the main
ready function, I add the following code:
$("<a href='#' id='expandAll'>Expand All</a>").insertAfter("h1");

$("#expandAll").click(function (event) {
event.preventDefault();

if ($(this).html() == "Expand All") {
$("#faq dd").show();


Free download pdf