Part A (25 points): Javascript
In this step you will make a modification to the FAQs
application discussed in chapter 6 (that application is provided as
your starting point in the zip file). When you’re done, this
application will work much 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 text, the
other answers must be hidden.
After downloading, unzipping and loading the netbeans project,
double check that the application works as described in the
text. Then: 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 aren’t 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 weren’t clicked. (Hint: the
one that has been clicked is the ‘this’ element).
This is the code i have but it is not perfect
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2
element
window.onload = function() {
// get the h2 tags
var faqs = $("faqs");
var h2Elements =
faqs.getElementsByTagName("h2");
function toggle(){
var h2;
for (var i = 0; i < h2Elements.length; i++ )
{
h2 = h2Elements;
h2Elements.onclick =
toggle;
if (h2 === this) {
if
(!h2.hasAttribute("class") ) {
hide(h2);
}else {
show(h2);
}
}else{
hide(h2);
}
}
}
/*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
function show(h2) {
var div = h2.nextElementSibling;
h2.removeAttribute("class");
div.setAttribute("class","open");
}
// if (h2.hasAttribute("class")) {
//
h2.removeAttribute("class");
//} else {
// h2.setAttribute("class",
"minus");
//}
// toggle div visibility by adding or removing a
class
function hide(h2) {
var div = h2.nextElementSibling;
h2.setAttribute("class","minus");
div.removeAttribute("class");
}
var div;
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class",
"open");
} ;
//};
// attach event handler for each h2 tag
for (var i = 0; i<h2Elements.length; i++) {
h2Elements.Onclick = toggle;
hide(h2Elements);
};
// set focus on first h2 tag's <a> tag
h2Elements[0].firstChild.focus();
};
Part A (25 points): Javascript In this step you will make a modification to the FAQs application discussed in chapter 6
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am