- "Queries about Javascript answered with a drop-down twist

Having some trouble with setting up a straightforward FAQ dropdown feature. Could someone lend a hand and see what might be going wrong?

Appreciate your help!

CSS

#faqs h3    { cursor:pointer; }
#faqs h3.active { color:#d74646; }
#faqs div { height:0; overflow:hidden; position:relative; }
#faqs div p { padding:0; margin-bottom:15px; } 

JavaScript:

$(document).ready(function() {
    $('#faqs h3').each(function() {
        var tis = $(this), 
            state = false, 
            answer = tis.next('div')
                        .hide()
                        .css('height','auto')
                        .slideUp();

            tis.click(function() {
                state = !state;
                answer.slideToggle(state);
                tis.toggleClass('active',state);
            });
    });
});

HTML

<div id="faqs">
    <h3>Question 1:</h3>
        <div>
            <p>Answer to Question 1.</p>
        </div>
    <h3>Question 2:</h3>
        <div>
            <p>Answer to Question 2.</p>
        </div>
</div>

Answer №1

If you're looking for the necessary functions, check out the following:

HTML

<div id="QA">
  <ul>
    <li>Question 1</li>
    <li>Answer 1</li>
    <li>Question 2</li>
    <li>Answer 2</li>
  </ul>
  <ul>
    <li>Question 3</li>
    <li>Answer 3</li>
    <li>Question 4</li>
    <li>Answer 4</li>
  </ul>

</div> 

JavaScript:

<script type="text/javascript">
    function toggle(tag) {
        var x=document.getElementsByName(tag)[0];
        var a = x.parentNode
        if (a.style.display=='block'){
            a.style.display='none'
        }else{
            a.style.display='block'     
        }
    }


    function init() {
        //this function will add show hide functionality to paired list items,
        //as long as the answer is a list item straight after the question list item.
        //You can also have as many separate lists as you want.
        //all lists must be contained within a div with id QA

        var obj = document.getElementById('QA');
        var elements = obj.getElementsByTagName('li');
               var index = 1 
        //add javascript to question elements
              //you could also add styling to question elements here
        for (var i=0; i < elements.length; i+=2){
            var element = elements[i]; 
            element.innerHTML = "<a href='javascript:toggle(" + index + ")'>" + element.innerHTML + "</a>"
            index = index + 1
        } 
        //add bookmark to answer elements and add styling
        var index = 1
        for (var i=1; i < elements.length; i+=2){
            var element = elements[i]; 
            element.innerHTML = "<a name='" + index + "' id='" + index + "'></a>" + element.innerHTML 
            index = index + 1
                 element.style.padding = '0px 0px 10px 20px' //add indent to answer
                       element.style.listStyleType = 'none' //remove bullet
            element.style.display = 'none' //hide answer element
        }       
     }


window.onload = init; 

</script>

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

Is there a way to update a JSON file using React?

I'm looking for a solution to update a JSON file in React. Is it possible? Below is the code snippet that executes when an HTML element is clicked. Ultimately, it invokes VoteTracking, the function responsible for updating the JSON file. handleC ...

Display the information stored in an array onto the console using console.log in Angular with Typescript

.html file <div class="container" *ngFor="let info of (this.info || [])"> <h5 class="card-title" (click)="getInfo()">{{info.paragraph1}}</h5> </div> .ts file getInfo () { *****console.lo ...

The for loop in JavaScript fails to verify the contents of an array and instead shows a message in a designated

The message for leap year is not appearing in the designated element Uncertain why the message isn't showing after the for loop const year = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032]; for (var i = 0; i < ye ...

Undefined method error encountered within Vue.js nested ref structure

My component structure is three levels deep and it's set up like this: - container - section-1 // section1Ref - form-1 // form1Ref The submit method in the container component will call the submit method in section-1 using this.$refs.section1R ...

Getting the time difference relative to the current time using date-fns from a MySQL datetime - a step

I am trying to implement a relative time feature like ... ago in my react blog posts without relying on moment.js. The date of the post is stored in mysql using the datatime data type, for example 2023-02-01 21:25:33 This is what I have attempted in the c ...

What is the best way to incorporate additional data into a TypeScript object that is structured as JSON?

I'm exploring ways to add more elements to an object, but I'm uncertain about the process. My attempts to push data into the object have been unsuccessful. people = [{ name: 'robert', year: 1993 }]; //I aim to achieve this peopl ...

"Handling API Calls with AngularJS: Dealing with the [object object] Response

Looking for some guidance on pulling a list of articles from the NPR API. I have a functioning URL that returns JSON data. However, in my controller code, I seem to be having trouble accessing the object. When I use console.log to check, it just shows [obj ...

I'm looking for a Visual Studio add-in that can identify and flag any unused CSS classes or IDs within the entire solution

Exactly as the headline suggests. If not, what are some reliable online services you've tried for decluttering oversized stylesheets? ...

The BeautifulSoup parsing result differs from the code of the original HTML page

Lately, I've been using BeautifulSoup4 to scrape data from Spotify Charts. It's been working smoothly for a few weeks until today when it suddenly started giving NaN values for all the entries... I suspect that the issue lies in the parsed HTML ...

Hover events in the browser are currently operating at a sluggish pace

When I hover over a photo, an overlay is supposed to appear. However, if I move the mouse quickly (from the top to the bottom of the page, for example), the overlay remains visible even after I stop hovering over the photo. I have tried different event ha ...

How can HTML be utilized to create a brief description?

I want to insert a link into the brief description that says "Read More..." which will direct the buyer to the main description further down on the product page when clicked. Can someone please provide guidance on how to achieve this? The URL for the link ...

Is Storybook webpack stuck in a loop, rebuilding and reloading constantly?

While working on a NextJS project with Storybook, I am encountering a recurring issue where the webpack keeps rebuilding continuously without stopping. This relentless rebuilding process puts a strain on my CPU and drains the battery of my device. Even aft ...

Retrieve data from API using ReactJS and passing parameters to the request

I am trying to retrieve information from the API based on the data I am sending, but encountering two issues: Initially, I hardcoded the information being sent to the API (year and term) as it should return the data I am trying to store, however, it is ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

The FindProxyForURL function in a pac (proxy-auto-config) file is not compatible with the IE browser

After struggling for three days, we are still unable to solve a peculiar technical issue and now seek your assistance. The PAC (Proxy Auto-Config) file we have created works flawlessly in all browsers except for Internet Explorer (IE). The URL in questio ...

How can you sustain a backend connection using NodeJS as users navigate through different pages?

Currently, I am establishing connections through thrift (node-thrift) with a backend server for api calls. The communication is bidirectional (push/pull) to NodeJS. As users navigate various URLs and Node serves jade templates and javascript files using C ...

Textfield style in Struts2 customization

How can I change the appearance of the textfield? [https://i.sstatic.net/TkQ0i.png] I am trying to remove the background color The code snippet in question: <s:form action ="Update_datos_XML"> <s:hidden id="id" name="id_sesion" value=" ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of ...