Display or conceal a div element individually

My task involves modifying this code, which is the original version of a FAQ with three answers that can be toggled to show or hide on click. I need to revise it so that only one answer is displayed at a time and the others close. I received advice to use a for loop to iterate through the array of h2 elements and remove the class attribute for all h2 elements except the one that was clicked.

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

// event handler for clicking 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 <a> tag
    h2Elements[0].firstChild.focus();       
};

Answer №1

The provided HTML code for the script:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Frequently Asked Questions</title>
    <link rel="stylesheet" href="styles.css">
    <script src="faqs.js"></script>     
</head>

<body>
    <main id="faqs">
        <h1>JavaScript FAQs</h1>
        <h2><a href="#" >What is JavaScript?</a></h2>
        <div>
            <p>JavaScript is a versatile programming language integrated into all major web browsers, enhancing website interactivity and reducing server requests.</p>
        </div>
        <h2><a href="#">What is jQuery?</a></h2>
        <div>
            <p>jQuery is a powerful library of essential JavaScript functions commonly used in web development projects.</p>
        </div>
        <h2><a href="#">Why is jQuery so popular?</a></h2>
        <div>
            <p>Three main reasons contribute to jQuery's popularity:</p>
            <ul>
                <li>It is free to use.</li>
                <li>Increases productivity by enabling quicker development.</li>
                <li>Offers cross-browser compatibility for all functions.</li>
            </ul>
        </div>
    </main>
</body>
</html>

CSS styles for the script:

* {
    margin: 0;
    padding: 0;
}
body {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 87.5%;
    width: 650px;
    margin: 0 auto;
    border: 3px solid blue;
    padding: 15px 25px;
}
h1 { 
    font-size: 150%;
}
h2 {
    font-size: 120%;
    padding: .25em 0 .25em 25px;
    cursor: pointer;
    background: url(images/plus.png) no-repeat left center;
}
h2.minus {
    background: url(images/minus.png) no-repeat left center;
}
a {
    color: black;
    text-decoration: none; 
}
a:focus, a:hover { 
    color: blue; 
}
div {
    display: none;
}
div.open {
    display: block;
}
ul {
    padding-left: 45px;
}
li {
    padding-bottom: .25em;
}
p {
    padding-bottom: .25em;
    padding-left: 25px;
}

Answer №2

Here is a potential solution that might work for you, assuming your current script/markup is functioning correctly. Unfortunately, I am unable to test it without access to the HTML/CSS files.

The code essentially loops through the FAQ items when one is clicked, hiding them if they are not the clicked element and showing them if they are - there won't be a toggle effect if the same item is clicked twice, as one will always remain open.

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

    // 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 accordionClick(){
           var h2;
           for(var i=0; i < h2Elements.length; i++){
             h2 = h2Elements[i]; 
             if(h2 == this){ // The item we clicked
               if(!h2.hasAttribute("class")){ // If it's open
                 closeItem(h2);
               } else{ // If not 
                 openItem(h2); 
               }
             } else{ // Not the item we clicked so it should be closed
               closeItem(h2);
             }
           }
        }
      
        function openItem(h2){
            var div = h2.nextElementSibling;
            h2.removeAttribute("class")
            div.setAttribute("class", "open");
        }
      
        function closeItem(h2){
            var div = h2.nextElementSibling;
            h2.setAttribute("class", "minus")
            div.removeAttribute("class");
        }
      
        // attach event handler for each h2 tag and initialize classes     
        for (var i = 0; i < h2Elements.length; i++ ) {
            h2Elements[i].onclick = accordionClick;
            closeItem(h2Elements[i]);
        }

        // set focus on first h2 tag's <a> tag
        h2Elements[0].firstChild.focus();       
    };
* {
    margin: 0;
    padding: 0;
}
body {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 87.5%;
    width: 650px;
    margin: 0 auto;
    border: 3px solid blue;
    padding: 15px 25px;
}
h1 { 
    font-size: 150%;
}
h2 {
    font-size: 120%;
    padding: .25em 0 .25em 25px;
    cursor: pointer;
    background: url(images/plus.png) no-repeat left center;
}
h2.minus {
    background: url(images/minus.png) no-repeat left center;
}
a {
    color: black;
    text-decoration: none; 
}
a:focus, a:hover { 
    color: blue; 
}
div {
    display: none;
}
div.open {
    display: block;
}
ul {
    padding-left: 45px;
}
li {
    padding-bottom: .25em;
}
p {
    padding-bottom: .25em;
    padding-left: 25px;
}
<main id="faqs">
        <h1>JavaScript FAQs</h1>
        <h2><a href="#" >What is JavaScript?</a></h2>
        <div>
            <p>JavaScript is a programming language that's built into the major web browsers.
                It makes web pages more responsive and saves round trips to the server.
            </p>
        </div>
        <h2><a href="#">What is jQuery?</a></h2>
        <div>
            <p>jQuery is a library of the JavaScript functions that you're most likely 
               to need as you develop web sites.
            </p>
        </div>
        <h2><a href="#">Why is jQuery becoming so popular?</a></h2>
        <div>
            <p>Three reasons:</p>
            <ul>
                <li>It's free.</li>
                <li>It lets you get more done in less time.</li>
                <li>All of its functions are cross-browser compatible.</li>
            </ul>
        </div>
    </main>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Error: Unable to access the property 'fontSize' as it is undefined

<!DOCTYPE HTML> <html> <head> <title>Interactive Web Page</title> <link id="mycss" rel="stylesheet" href="mycss.css"> <script> function resizeText(size) { va ...

Tips for effectively dividing React application components

Jumping into React to build an application seemed like a good idea at first, but now I realize the complexity of it. Let me walk you through my plan and see if it aligns with best practices: The goal is to develop a React App for organizing the subjects I ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

Managing AJAX requests using Express JS

Currently facing an issue with handling ajax requests using ExpressJS. Whenever I click on an anchor tag, the entire page reloads instead of handling the ajax request on the client side. I am looking to ensure that clicking on any of these links triggers ...

What steps are involved in generating the JSON Array string shown below?

Looking for assistance on creating and sending a JSON Array string, here is an example of what I need: I am utilizing the JSON Framework, which can parse JSON array but I'm unsure how to create a JSON Array. { "deferred": [ { "API": "Test1" ...

How come my reducer isn't changing the state of my store with ImmutableJS?

I have the following code within my reducer: const copy_states = fromJS(state); const i_copy_jobs = copy_states.get('calendar_jobs').get(s_from_day_key).get(s_dept_id).get(s_job_id); let i_calend ...

Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when th ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...

Utilize Boolean operators such as AND, OR, and NOT to locate specific keywords within a text, mirroring the search capabilities

Is it possible to perform Google-style searches in strings using operators like "or", "and" and "not" with regular expressions? For instance, I aim to search for the words "Javascript", "PHP" and "Perl" within a given string in these ways: Javascript an ...

Display the HTML element prior to initiating the synchronous AJAX request

I'm looking to display a <div> upon clicking submit before triggering $.ajax() Here's my HTML: <div id="waiting_div"></div> This is the CSS: #waiting_div { position: fixed; top: 0px; left: 0px; height: 100%; ...

CSS - Achieving full width on hover even when the element has a specified width setting

I am encountering an issue with my CSS. Although I have successfully centered everything, I am facing a problem with the hover effect in CSS. Whenever I apply the active class or hover over an li element, the background color expands to 100%. Additionally, ...

Trouble with the 'uppercase' package in Node.js: Receiving ERR_REQUIRE_ESM error while utilizing the require() function

I am encountering a problem with the 'upper-case' module while developing my Node.js application. My intention is to utilize the upper-case module to convert a string to uppercase, but I'm running into difficulties involving ESM and require( ...

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

Using a PHP WordPress Loop, eliminate the comma following the final object in the Schema array

My Google Schema Markup for a "Product" includes a loop that displays "Reviews". Below is an excerpt of the code: "review": [ <?php $args = array( 'post_type' => 'my_reviews', & ...

Redux does not have the capability to insert an object into an array

I'm currently learning about redux and I've encountered an issue trying to add multiple objects into the initialState array. I attempted using the push() method, but it isn't working as expected. The submitter value is being passed to my act ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...

Alerting JavaScript with element Selector doesn't function at full capacity

I am currently implementing Notify JS from the following source : Below is the HTML code I am using: <div> <p><span class="elem-demo">aaaa</span></p> <script> $(".elem-demo").notify( "Hello Box" ...

Is it possible to pass the index variable of a for loop to a different function?

As a current bootcamp student, I have a question about passing the index of a for loop to another function. Specifically, I am trying to fetch data from an API (which provides me with a random cryptocurrency from an array) 4 times and then pass that data ...

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...