The Perfect Scrollbar feature is not functioning properly in conjunction with the accordion menu

I am having some trouble with implementing the Perfect Scrollbar alongside an accordion slider menu. The scrollbar is not working as expected, and you can view the fiddle here.

On initial page load, the scrollbar only appears for the first sub-menu after scrolling within the container. However, it does not update properly for the second and third sub-menus. I have attempted to use ps.update(); as suggested on various websites, but I am unsure if I am calling the function correctly.

Update:
I was able to resolve the issue and have shared the updated code snippet in case it helps someone else in the future. https://jsfiddle.net/prashu421/egkfxzrt/

      $(document).ready(function() {
        // Store variables
        //var ps = new PerfectScrollbar('.sub-menu');

        const container = document.querySelector('.sub-menu');
        const ps = new PerfectScrollbar(container);

        var accordion_head = $('.accordion > li > a'),
            accordion_body = $('.accordion li > .sub-menu');

        // Open the first tab on load
        accordion_head.first().addClass('active').next().slideDown('normal');

        // Click function
        accordion_head.on('click', function(event) {
            // Disable header links 
            ps.update();                
            event.preventDefault();

            // Show and hide the tabs on click
            if ($(this).attr('class') != 'active'){
                accordion_body.slideUp('normal');
                $(this).next().stop(true,true).slideToggle('normal');
                accordion_head.removeClass('active');
                $(this).addClass('active');
            }
        });
    });

Your assistance and input are greatly appreciated. Thank you.

Answer №1

Make sure to apply the perfect scrollbar to all container elements by using querySelectorAll('.sub-menu') and initializing the perfect scrollbar for each container:

$(document).ready(function() {
  const containers = document.querySelectorAll('.sub-menu');
  containers.forEach(container => {
    new PerfectScrollbar(container);
  });

  const accordion_head = $('.accordion > li > a');
  const accordion_body = $('.accordion li > .sub-menu');

  // Open the first tab on load
  accordion_head.first().addClass('active').next().slideDown('normal');

  // Click function
  accordion_head.on('click', function(event) {
    // Disable header links
    event.preventDefault();

    // Show and hide the tabs on click
    if ($(this).attr('class') != 'active') {
      accordion_body.slideUp('normal');
      $(this).next().stop(true, true).slideToggle('normal');
      accordion_head.removeClass('active');
      $(this).addClass('active');
    }
  });
});
.accordion,
.accordion ul,
.accordion li,
.accordion a,
.accordion span {
  margin: 0;
  padding: 0;
  border: none;
  outline: none;
}

...
/* Styles continued */
...

#bloc-accordeon p {
  Font-family: Trebuchet MS, Arial, Helvetica;
  font-size: 12px;
  font-weight: bold;
  color: #797979;
} 
<script src="https://rawgit.com/utatti/perfect-scrollbar/master/dist/perfect-scrollbar.js"></script>
<link href="https://rawgit.com/utatti/perfect-scrollbar/master/css/perfect-scrollbar.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bloc-accordeon">

<!-- HTML structure with accordion and sub-menus -->

</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

Creating a jQuery AJAX form that allows users to upload an image, submit the form, and store the entered values in a MySQL database

I am struggling with an HTML form that I am trying to submit using jQuery's $.ajax(); The form needs to: 1. Upload an image to a directory with error checks 2. Save the image path to a MySQL database 3. Insert two other form values (input and select) ...

How come I am able to successfully send a Post request through Postman, but encountering issues when trying to do the same

I am facing an issue with my NodeJs/Express Webservice. When I send a POST request to the webservice using Postman, it works fine. However, when I try to send a POST request using JavaScript, I encounter the error {message: "Cannot read property 'path ...

Creating a schedule by aligning each day of the week with its corresponding date

weekly calendar<----img here--! I am looking to enhance my weekly table by incorporating a calendar system into it. Instead of just displaying the year in the image, I want it to showcase a 7-day week layout (for example: 12/20/20 - 12/27/2020), with ...

Having trouble parsing a JSON string in your JavaScript code?

As a java developer transitioning to JavaScript, I'm faced with the task of parsing a JSON string retrieved from a WebService. Here is the JSON String: { "myArrayList": [ { "myHashMap": { "firstName": "Clara", ...

Creating a JavaScript array in Rails 4 based on current data without the need to reload the webpage

Currently in my rails 4 app, I am working on a unique tags validation using jquery validate to ensure that tags are not duplicated before they can be added to an item. The tag list structure is as follows: <div id="taglist"> <span class="label ...

What is the solution for fixing the '$ not defined error' in a .js file with $ajax code?

var example = document.createElement("SCRIPT"); example.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"; var nodeScript= document.createTextNode("function test() {console.log('test message');$.ajax({ type: \"POST&bs ...

spontaneous angular rotations in a constantly shifting CSS environment

Is it possible to apply a random CSS rotation to an image just once, rather than having it continuously spin when hovering over a leaflet map? http://jsfiddle.net/J03rgPf/mzwwfav4/3/ I want the random CSS rotation to be set only one time. How can I achie ...

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...

Efficiently accomplishing this task with jQuery

Below is a compilation of items along with their corresponding item hashes: 347366834 AceofSpades 460724140 TheJadeRabbit 814876685 TrinityGhoul 1345867570 SweetBusiness 1508896098 TheWardcliffCoil 1852863732 Wavesplitter 2044500762 TheQueenbreake ...

Innovative and interactive animated data display

I've taken inspiration from an example and expanded the code to achieve the following: Dynamic height adjustment Accessibility without JavaScript enabled Is this implementation correct? Can it be expected to function properly on most browsers? You ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

variable identifier looping through elements

I'm attempting to assign a dynamic ID to my div using ng-repeat. Here's an example: <div id="$index" ng-repeat="repeat in results.myJsonResults"> <div id="$index" ng-click="saveID($index)" ng-repeat="subRepeat in results.myJsonResul ...

Module for React Native that enables users to select and copy text within a specified view

Is there a feature that enables users to highlight and copy text from within a view? If not, is there a method to identify all "Text" type elements and extract the text they contain? <View> <Text>Text1</Text> <Text>Text2</Text& ...

The PHP file on my local WAMP server seems to be having trouble retrieving inputs from the HTML's GET or POST methods

<!DOCTYPE HTML> <html> <body> <form action="testrun.php" method="GET"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </bo ...

Looking to implement a scroll bar in your PhoneGap mobile app for Android?

Encountering an issue with my Android PhoneGap mobile website application. I have implemented a scroll bar in the application which works perfectly on PC. However, when testing on an Android device (mobile phone), the scroll bar does not enable. ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

Entering an incorrect pin code results in a Bad Request (400) error being displayed

We have integrated a pin code API provided by our logistic partner into the Shopify checkout page. The API works perfectly when a valid pin code is entered, returning a JSON response. However, if an invalid (non-serviceable) pin code is entered (a 6-digit ...

What steps should be taken to resolve the error message "TypeError: Cannot read properties of undefined (reading 'toLowerCase')?"

After creating a basic search bar, I encountered an issue when typing in it for the first time: TypeError: Cannot read properties of undefined (reading 'toLowerCase') However, when I closed the pop-up and tried again, the search bar worked prope ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...