Certain JavaScript code might fail to load on WordPress

I've been struggling to troubleshoot an issue with a JavaScript accordion menu on my WordPress site. When I try to click the accordion button, it doesn't reveal the hidden content beneath it. I've attempted various solutions, but none have seemed to work for me as a beginner in this field. Here's the code I'm working with:

JavaScript:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[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 panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    });
}

CSS:

/* Styling for buttons used to open and close the accordion panel */
.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
}

/* Adding background color when clicked or hovered over */
.active, .accordion:hover {
    background-color: #ccc;
}

/* Style for the accordion panel - initially hidden */
.panel {
    padding: 0 18px;
    background-color: white;
    display: none;
    overflow: hidden;
} 

HTML:

<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>

When using Firefox console, the error message TypeError: panel is null is pointing to the line

if (panel.style.display === "block") {
. While testing with alert('hi');, everything seems to be loading fine, so the problem may lie within that specific piece of code.

Answer №1

I tested your code in a jsfiddle and it appears to be functioning correctly, both buttons are able to reveal the hidden content.

Check out the working example here

It seems like your current code is good to go as long as you add another accordion button.

<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
  <p>Lorem ipsum...</p>
</div>

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

Leveraging Angular 2 directives in TypeScript to bind a value from a custom control to an HTML control

I have created a unique custom directive named "my-text-box", and within this directive, I am utilizing the HTML control <input>. I want to pass values from my custom control to the HTML input control. In Angular 1, I would simply do something like & ...

Declaring types globally in Visual Studio Code for JavaScript programming

My /typings/$app.d.ts file has the following structure: declare class App { test: object } export const $app: App; https://i.sstatic.net/3HW7M.png In order to enable intellisense, I have to auto-import it, resulting in a line like this at the begin ...

Change the dropdown header behavior from hovering over it to clicking on it

This snippet of code is integrated into our header to showcase the cart. Currently, the dropdown appears when hovering over it. Is there a way to adjust this so that the dropdown shows up when onclick? <a href="#header-cart" class="skip-link skip-cart ...

Extracting JavaScript OnClick button using Selenium

I'm having trouble extracting the email address from the following URL: https://www.iolproperty.co.za/view-property.jsp?PID=2000026825 that is only visible after clicking on the "Show email address" button. However, every time I attempt to click and r ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Increase the border thickness on the top side of the div

To enhance the design of the .menu div, I decided to include an additional border at the top. Initially, I incorporated top and bottom borders using box-shadow, followed by traditional borders using border-bottom, border-left, and border-right properties. ...

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...

How can I resize the border to match the size of the text inside it?

Check out the following image to see how it appears:https://i.sstatic.net/RkMqI.png Here is an example code snippet of a message: .allMsg { width: 100%; } .self { border-radius: 1rem; background-color: #28a745; text-align: right; padding-lef ...

Concise conditional statement without assignment using shorthand syntax

Can a block like this be shortened in any way? if (popupIsvisible === false) { this.show(); } else { this.hide(); } I attempted the following: popupIsvisible === false? this.show() : this.hide(); However, I encountered the following error: Expect ...

"Consolidating into one large package, Less is compiled and bundled together

Is there a way to display only the CSS being utilized on a webpage after it loads, rather than serving all compiled .less files as one big .css file? In addition, I am interested in having a sourcemap of the .less files shown in the browser for debugging ...

Instructions on creating an "already clicked" style for an <a> href

Is there a solution to display my href as already clicked? I'm looking for a property or method that does not involve css or javascript. ...

The function addView is not recognized by Framework7

I am embarking on the journey of creating a Cordova app with Framework7 as my UI framework. My goal is to adopt inline pages as the architectural layout, but I am encountering an error in the console during project setup: An error message of "Uncaught Typ ...

In Javascript, how are instance members within a constructor accessible to methods defined on constructor prototypes?

As I dive into learning about prototypes in JavaScript and the prototype chain, a particular issue has me puzzled. Consider this constructor: function Circle() { this.radius = 1; } let c1 = new Circle(); Circle.prototype.toString = function() { ...

The jQuery tooltip fails to function properly after the AJAX content is loaded

I have been using a tooltip script that can be found at: This is the script I am using, with a few modifications: $(document).ready(function() { $("body").on("mouseover", ".tip_trigger", function(){ tip = $(this).find('.tip&apos ...

What Makes Sports Illustrated's Gallery Pages Load So Quickly?

After thoroughly examining their code, I'm still puzzled. Are they loading complete new pages, or are they utilizing jQuery to modify the browser's URL while keeping most of the page unchanged? I'm currently inspecting the source of this pa ...

What could be causing the compatibility issue between fr units and grid-template-rows in CSS grid?

I'm having trouble getting the row height to change using fr units in my grid-template-rows. It seems to work fine with other units like pixels, but not with fr. I find it confusing that the fr units work perfectly fine with grid-template-columns, so ...

Storing data for extended periods in NodeJS

Currently, I have a node server up and running. To maintain its uptime when I'm not actively developing, I utilize npm forever. However, for editing purposes (such as restarting the app upon edits or uploads), I rely on npm nodemon. After restarting ...

Dynamic div with height controlled by the content of the background image

I'm trying to figure out how to make a div with a background image of 100% width always maintain the aspect ratio of the image for its height. Is there a way to achieve this? In simpler terms, when I resize the page, I want the div to scale down whil ...

The API for /api/addproducts has been resolved without a response being sent, potentially causing delays in processing requests

A response was not sent for the /api/addproducts API, which can lead to delays in processing requests. Below is the code for the add product API that I have been working on: I've debugged it using the console, but I'm still struggling to find t ...

Pass data as json from javascript to php

After users perform actions on a page and click "next," the goal is to redirect them to a PHP file named "Step2.php" along with specific JSON data. The constructed JSON string is as follows: [{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image ...