1

I have got a javascript based menu generator that is from an external source. The menu functionality occurs via a click event bound to a specific ID... pretty standard.

What I want to do is perform another action on the DOM AFTER that click event fires.

I would rather not hack the code that came in the menu package.

I tried attaching my own click handler - but there isn't an obvious way of ensuring my click handler fires AFTER the menu system's handler. One approach I considered was basing an event on the addition/removal of a class that occurs with the menu system's click handler. But - I quickly found that there is no event based on the change of class on an element (that I know of).

Any ideas? (without hacking the original menu system's js)

2
  • This might be helpful (Look at the updated part of the answer): stackoverflow.com/a/19401707/6400614 Commented Sep 21, 2019 at 16:28
  • Thank you for the quick response. I saw that - or one similar. I don't think it will work because it is the Navigation System that actually changes the class. Yes - if I was changing the class, I wouldn't need another handler, I'd just do the additional work on the DOM then and there :) Commented Sep 21, 2019 at 16:43

1 Answer 1

1

You can use the javascirpt Mutation Observer, here is a great article about the subject : Listening to the DOM changes with MutationObserver

OR in an old fashion

If I understand, (1) you can add your own click event listener, (2) you want execute your code after a class name change on the menu element.

In that case, you can use a setInterval to check if the class has changed and if so, trigger your action.

Something like that :

myOnClickFunction(){

    var menu = document.querySelector('#MyMenuID');

    var timer = setInterval(() => {

        if(menu.classList.contains('TheClassNameYouWantToCheck')){
            //Clear the interval 
            clearInterval(timer);

            //Execute your actions here

        }

    }, 50);


    //You can also add a maximum checking  time
    //after 5 seconds the function stop checking for changes
    setTimeout(()=>clearInterval(timer), 5000);

}
Sign up to request clarification or add additional context in comments.

1 Comment

Both sound like good ideas. I'm curious about the Mutation Observer. I did see that but it seemed like dropping a 1000 lb bomb when a mousetrap would do the trick :) Never thought of setInterval... I could use it here or elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.