Troubleshooting a JavaScript Script Issue in a NextJs Class

I have been working on my website and decided to incorporate an FAQ page. I used a template for the FAQ section and tried to implement Javascript in my NextJs project, but unfortunately, it's not functioning as expected.

var faq = document.getElementsByClassName("faqpage");
var i;

for (i = 0; i < faq.length; i++) {
    faq[i].addEventListener("click", function () {
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");
        

        /* Toggle between hiding and showing the active panel */
        var body = this.nextElementSibling;
        if (body.style.display === "block") {
            body.style.display = "none";
        } else {
            body.style.display = "block";
        }
    }); 
}
var cpt = document.getElementsByClassName("faqbody");
var i; 

for (i = 0; i < faq.length; i++) {
    cpt[i].addEventListener("click", function () {
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");
        

        /* Toggle between hiding and showing the active panel */
        var body = this.nextElementSibling;
        if (body.style.display === "block") {
            body.style.display = "none";
        } else {
            body.style.display = "block";
            
        }
    }); 
}
.Faq {
      background-color: rgba(46,40,35,255); 
      padding-top: 50px;
      padding-bottom: 150px;
}
.Faq h2 {
      color: white;
      text-align: center;
      font-size: 4vh;
      margin-bottom: 20px;
}
.faqcontainer{
      display: flex;
      justify-content: center;
      flex-direction: column;
      }
      .hrline{
        width: 62%;
        margin: auto;
        margin-top: 20px;
      }
      .faqpage {
          cursor: pointer;
          padding: 30px 20px;
          width: 60%;
          border: none;
          font-size: 25px;
          font-weight: 600; 
          outline: none;
          transition: 0.4s;
          margin: auto;
          color: #EC2628;
      }

      .faqbody{
            margin: auto;
            /* text-align: center; */
            width: 50%;
            line-height: 30px;
            font-size: 20px; 
            padding: 0 18px; 
            display: none;
            overflow: hidden;
            padding-bottom: 20px;
      }
  .faqpage:after {
      content: '\002B';
      /* Unicode character for "plus" sign (+) */
      font-size: 35px;
      font-weight: 100;
      color: white;
      
      float: right;
      transition-duration: 0.5s;
  }
  .active:after {
      transform: rotate(45deg);
      /* Unicode character for "minus" sign (-) */
      font-weight: 100; 
  }
<div className={styles.Faq}>

                        <h2>FAQ</h2>

                        <div className={styles.faqone}>                 
                              <h1 className={styles.faqpage}>How can I join the community?</h1>
                              <div className={styles.faqbody}>
                                    <p>We have a very active community and we welcome new members with open arms! Come and chat with us on Discord.</p>
                              </div>
                        </div>
                        <hr className={styles.hrline}/>
                        <div className={styles.faqtwo}>                 
                              <h1 className={styles.faqpage}>How can I join the community?</h1>
                              <div className={styles.faqbody}>
                                    <p>We have a very active community and we welcome new members with open arms! Come and chat with us on Discord.</p>
                              </div>
                        </div>
                        <hr className={styles.hrline}/>
                        <div className={styles.faqthree}>                 
                              <h1 className={styles.faqpage}>How can I join the community?</h1>
                              <div className={styles.faqbody}>
                                    <p>We have a very active community and we welcome new members with open arms! Come and chat with us on Discord.</p>
                              </div>
                        </div>
                        <hr className={styles.hrline}/>
                        <div className={styles.faqfour}>                 
                              <h1 className={styles.faqpage}>How can I join the community?</h1>
                              <div className={styles.faqbody}>
                                    <p>We have a very active community and we welcome new members with open arms! Come and chat with us on Discord.</p>
                              </div>
                        </div>
                        <hr className={styles.hrline}/>

                        <Script src="../components/FAQLOC.js"></Script>
                  </div>

After checking, I suspected that the issue might be related to the classes and the handling of classes using Javascript within Nextjs. However, I am unsure about how to resolve this problem.

The code snippet above provides insights into my CODE! Is there anyone who could assist me in resolving this?

Answer №1

By default, components in Nextjs are server-side rendered which limits access to the document object. One way to work around this is by dynamically importing your component and disabling SSR. Check out more details here: https://nextjs.org/docs/advanced-features/dynamic-import

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

Are you looking for outcomes related to Bootstrap typeahead feature?

I am facing an issue with returning results for the bootstrap typeahead after making an ajax request. Strangely, it works fine without initiating the ajax request. The code that doesn't work: $(".typeahead").typeahead({ source: function(query, pr ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

displaying error message after calling API on Node.js express server

I'm currently working on error handling on the front end, using responses from my Express server. The process involves sending data from the front end to the Express server via a POST request. The endpoint (referenced as /endpoint below) then communic ...

Tips on using the $.grep() method in jQuery to filter dynamic inputs

When using the "grep" function in jQuery to filter data, the code sample below works well for static conditions. However, if the "name" and "school" parameters have multiple values, how can we filter them? Let's say I receive the name and school from ...

What is the method for programming a Discord bot to respond to your messages?

As a beginner in coding, I have been working on creating a bot that can respond with whatever is said after the command !say. For example - if you type !say hello, the bot will reply with "hello". This is what I have attempted: let args = message.content ...

Stop all file uploads using jQuery

I have integrated the jQuery File Upload plugin () into my website for image uploads. Here is my code snippet: $('#fileupload').fileupload({ url: 'server/index.php', dataType: 'json', dropZone: $('#dropzone&a ...

Issue with data retrieval from Firebase snapshot reference

While working with Firebase, I encountered an issue related to setting and getting priorities of items in a list of people. Surprisingly, the functionality seems to work fine in one function but throws an error in another. When trying to get the priority ...

Created a custom function that includes a specific target href parameter

I have a website that implements role-based authentication, where the application displayed is dependent on the user's role. The code for this functionality is as follows: <asp:Repeater ID="ui_rprApp" runat="server" DataSourceID="odsApp"> ...

Assign the value in the text box to the PHP session variable

Currently, I am developing a PHP "interactive text game" as a part of my assignment project. My task involves creating a user interface where users input information (such as character names) into text boxes that appear sequentially as they complete the p ...

Nextjs: utilizing static class or employing a use function

Exploring Methods to Create a Tools Class/Function in NextJS I am considering two different approaches for this task. Using Static Class: class Tools { static titleCase(value: string) { return value.charAt(0).toUpperCase() + value.slice(1). ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

JQuery script fails to load in the head section while dynamically generating an HTML page with JavaScript

Using JavaScript, I have created a new window dynamically and added some HTML code to it. However, when I try to insert a script link into the HTML head, it fails to load when the window is open. <script type="text/javascript"> function newWindo ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

Tips for utilizing identical properties across numerous styled elements:

Utilizing the styled-components library, I have enhanced the header components from the Blueprintjs library. The current template for the H6 component appears as follows: export const DH6 = styled(H6)` color: ${(props) => (props.white ? "white&qu ...

Tips for including an additional label on a data point within a scatter plot using the Highcharts JavaScript framework

Incorporating the Highcharts JavaScript library, I am visualizing float values by passing them from PHP to the JS code. In the image below, you can observe that upon hovering over each point, the corresponding axes values are displayed along with the text ...

Navigate through two distinct elements by categorizing them based on their types

After completing the frontend design, I moved on to integrating the backend and encountered an issue. If anyone can offer assistance or even a hint, it would be greatly appreciated. Visit the demo website for more insight. Initially, I hard coded the comp ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

Error with cookies in NextAuth and iteration issue in NextJs

I have encountered a persistent issue and I need assistance. The error that keeps popping up is as follows: - event compiled client and server successfully in 307 ms (168 modules) - event compiled client and server successfully (447 modules) - warn Fast Re ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

What is the method for importing .scss files throughout a Next.js application?

I'm looking to transform my React app into a Next.js app. In the current React setup, I have .scss CSS files being imported in various components. However, once I transfer the code to a Next.js environment, I encounter an error: Global CSS cannot be ...