Search code examples
javascriptjqueryhtmlcssmutation-observers

How to detect/listen for a class being added to an element on hover?


I have a class added to my navigation on hover .show-dropdown and I would like to disable my scroll when the nav is initiated.

Is a mutation observer the best way to go about doing this or is it overkill?

I want to do something simple like

if($('.show-dropdown').length > 0) {
  window.disableOnScroll = 1;
}

unfortunately, this never gets called when the hover is initiated, I believe it is because it is only checking for the class on-load.

Is a mutation observer my best bet? Or should it be only used to listen for a node/element being added to the dom rather than a class?


Solution

  • You can disable scroll when you enter an by subscribing to mouseover events.

    In order to enable scrolling again, you will need to listen to mouseleave events as well. When those events are fired, re-enable scrolling.

    An event delegator would be well suited for this so that you won't have to handle all the events in one place.