简体   繁体   中英

How to Add an Expand All button to a javascript/HTML project

I currently have a page that has content that expands when you click on a term, but as soon as you click on a new term the old one closes and the new one expands. The terms are loaded in from a google sheet onto the page. This is on a HTML page but the javascript code to do the work is the following:

// Address of the Google Sheets Database
var public_spreadsheet_url = 'sheet link here';

// Column Names from Google Sheets Database
let questionsColumn = "Question";
let answersColumn = "Answer";

window.addEventListener('DOMContentLoaded', init)   // Calls method init when Sheets has loaded

function init() {
Tabletop.init( { key: public_spreadsheet_url,
                 callback: showInfo,
                 simpleSheet: true } );
}

var unhiddenAnswer = "";

// Method that gets called when data has been pulled from Google Sheets
function showInfo(data) {
    var editButton = '<center><a style="border-bottom: none" href="' + public_spreadsheet_url + '"><button class="button admin">Edit</button></a></center>';

    // Injects the built HTML code into the div Dynamic
    document.getElementById("dynamic").innerHTML = buildFAQTable(data) + editButton;
}

// Builds the HTML Table code from the Database Data
function buildFAQTable(data) {
    var index = 0;
    var content = '<h2>Title Here</h2><div style="padding:0px 5%">';
    data.forEach(form => {
        content += '<h1 class="faq_question" onClick="unhideAnswer(' + index + ')">' + data[index][questionsColumn] + '</h1>';
        content += '<p id="answer' + index + '" class="hideAnswer">' + data[index][answersColumn] + '</p>';
        index++;
    });
  // Extends body to accomdate for tall footer on very small devices (e.g. iPhone 5/5S/SE)
  content += "<br></br><br></br>";
    return content;
}

// When a FAQ Question gets clicked on, this method will hide the currently displaying answer (if any), and
// Unhide the answer corresponding to the clicked on answer.
// If the currently displaying answer is the same as the answer corresponding to the clicked on question,
// it will be hidden and no new answer will be unhidden
function unhideAnswer(number) {
    var answerID = "answer" + number;
    if (answerID != unhiddenAnswer) {
        document.getElementById(answerID).classList.remove("hideAnswer");
    }
    if (unhiddenAnswer != "")
        document.getElementById(unhiddenAnswer).classList.add("hideAnswer");
    if (unhiddenAnswer == answerID)
        unhiddenAnswer = ""
    else
        unhiddenAnswer = answerID;
}

I want to now add an expand all/ collapse all button to give the user the option to open and view all the terms at one if needed. However, if not using the expand all button, the regular open and close functionality above should be used. I am new to javascript and am at a loss on the best way to implement this. Any help would be appreciated.

add a answer class to every answer, then you can loop through all of them with this query selector

// in your buildFAQTable fucntion
content += '<p id="answer' + index + '" class="hideAnswer answer">' + data[index][answersColumn] + '</p>';


document.querySelectorAll('.answer').forEach(answer => {
  // you can use toggle, add or remove to change the appearance of the answer
  answer.classList.toggle('hideAnswer')
})

i would also recomend you to check out some of the newer javascript features like string interpolation and avoid using var, but it is not so important if you are just starting out.

(i also refactored some of your code, this might make it a bit more readable)

// Address of the Google Sheets Database
const public_spreadsheet_url = 'sheet link here';

// Column Names from Google Sheets Database
const questionsColumn = "Question";
const answersColumn = "Answer";

function toggleAnswer(num) {
        const answer = document.getElementById(`answer${num}`);
        answer.classList.toggle('hideAnswer');
}

function hideAll() {
        document.querySelectorAll('answer').forEach(answer => {
                answer.classList.add('hideAnswer');
        })
}

function showAll() {
        document.querySelectorAll('answer').forEach(answer => {
                answer.classList.remove('hideAnswer');
        })
}

function buildFAQTable(data) {
        let index = 0;
        let content = '<h2>Title Here</h2><div style="padding:0px 5%">';

        for (i in data) {
                content += `<h1 class="faq_question" onClick="unhideAnswer(${i})">${data[i][questionsColumn]}</h1>`;
                content += `<p id="answer${i}" class="hideAnswer answer">${data[i][answersColumn]}</p>`;
        }

        content += "<br></br><br></br>";
        return content;
}

function showInfo(data) {
        const editButton = `<center><a style="border-bottom: none" href="${public_spreadsheet_url}"><button class="button admin">Edit</button></a></center>`;

        document.getElementById("dynamic").innerHTML = buildFAQTable(data) + editButton;
}

window.addEventListener('DOMContentLoaded', () => {
    Tabletop.init({
        key: public_spreadsheet_url,
        callback: showInfo,
        simpleSheet: true
    });
}, { once: true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM