0

I have a menu inside a div, which is closed/hidden by default. it opens when I click on it, with adding the class open to it.

<ul class="mydropdown-menu">
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
</ul>

<ul class="mydropdown-menu"> change to <ul class="mydropdown-menu open"> when menu is visible.

since this happens dynamically, can't use usual jquery's hasClass to determine whether it's there.

I heard about Mutation Observer and I tried few examples found on internet, but nothing seems to work out for me.

Can someone help me to achieve this?

I just need to know everytime my menu's ul element opens up/adds the open class to it, using mutation observers. how can I do this with jQuery?

Van Dyke
  • 23
  • 6
  • You can certainly do this using a MutationObserver (see the duplicate for instructions on how), but it's really a last resort. If your code controls when this menu opens you should add the functionality there. If it's a third party library, then check they don't raise any events which you can hook to instead. – Rory McCrossan Mar 05 '20 at 10:54
  • it's simple bootstrap navbar. it toggles class named open to change the state. the linked question didn't help me at all actually. so any help will be appreciated – Van Dyke Mar 05 '20 at 10:59
  • If you're using Bootstrap then the navbar uses the standard collapsible event model, eg `shown.bs.collapse`: https://jsfiddle.net/RoryMcCrossan/fybusknv/. With regard to the duplicate, it shows a full working example of how to set up a Mutation Observer to detect a class change. I'm not sure how much more explicit it could be. – Rory McCrossan Mar 05 '20 at 11:02

0 Answers0