Topic: Close dropdown on scroll

PerfectCamp priority asked 11 months ago


Does anyone know why I can't hide a dropdown using this code?

window.addEventListener('scroll', function() {
            // close any open dropdowns
            $('.dropdown-menu.show').each(function() {
                var dropdown = $(this).closest('.dropdown')[0];
                mdb.Dropdown.getInstance(dropdown).hide();
                //$(this).removeClass('show');
            });
        });

The console shows an error: Uncaught TypeError: Cannot read properties of null (reading 'hide'). I wish I knew the jQuery way to hide a dropdown but can't see any docs showing how to control them via jQuery. Can anyone help? I can close the drop down's via getting rid of the show class but I would rather do it via the API so it fades out. Thanks!


Kamila Pieńkowska staff answered 11 months ago


You were trying to getInstance from the wrong element. I've prepared a snippet for you: https://mdbootstrap.com/snippets/standard/kpienkowska/5263359


PerfectCamp priority answered 11 months ago


Thanks so much! Here is an updated simplified snippet using your solution.

window.addEventListener('scroll', function() {
            // close any open dropdowns
            $('.dropdown-toggle.show').each(function() {
                mdb.Dropdown.getInstance(this).hide();
            });
});


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 6.3.0
  • Device: PC
  • Browser: chrome
  • OS: win 11
  • Provided sample code: No
  • Provided link: No