Question: use strict; var $ = function(id) { return document.getElementById(id); }; // the event handler for the click event of each h2 element var toggle =

"use strict"; var $ = function(id) { return document.getElementById(id); };

// the event handler for the click event of each h2 element var toggle = function() { var h2 = this; // clicked h2 tag var div = h2.nextElementSibling; // h2 tag's sibling div tag

// toggle plus and minus image in h2 elements by adding or removing a class if (h2.hasAttribute("class")) { h2.removeAttribute("class"); } else { h2.setAttribute("class", "minus"); }

// toggle div visibility by adding or removing a class if (div.hasAttribute("class")) { div.removeAttribute("class"); } else { div.setAttribute("class", "open"); }

};

window.onload = function() { // get the h2 tags var faqs = $("faqs"); var h2Elements = faqs.getElementsByTagName("h2"); // attach event handler for each h2 tag for (var i = 0; i < h2Elements.length; i++ ) { h2Elements[i].onclick = toggle; } // set focus on first h2 tag's tag h2Elements[0].firstChild.focus(); };

FAQs

JavaScript FAQs

What is JavaScript?

JavaScript is a is a browser-based programming language that makes web pages more responsive and saves round trips to the server.

What is jQuery?

jQuery is a library of the JavaScript functions that you're most likely to need as you develop websites.

Why is jQuery becoming so popular?

Three reasons:

  • It's free.
  • It lets you get more done in less time.
  • All of its functions are cross-browser compatible.

Extra 6-3 Modify the FAQs

application

This exercise has you make a minor modification to the FAQs application. When

youre done, this application should work the same as before, except that only

one answer can be displayed at a time. In other words, when the user clicks on a

heading to display the answer, the other answers must be hidden.

1.

Open the HTML and JavaScript files in this

folder:

exercises_extra\ch06\faqs\

Then, run the applicat

ion to refresh your memory about how it works.

2.

Add code

to the

toggle() function so

only

one

answer can be displayed at a

time. To

do that,

create an

array

of the h2 elements.

Then, use

a for

loop

to go

through the h2

elements in

the array

and remove the class attribute for all h2

elements that arent the one that has been clicked. You also need to remove the

class attributes for all of the div siblings of the h2 elements that werent

clicked.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!