I have the following code that works, but if I click a panel and then click it again, the mutation observer fires twice on the second click. Does anyone know the cause of this and how to stop it?
I'm guessing it's because it fires once for the add class and once for the remove class. but if that's the case, the classList.contains shouldn't be true when you do the remove class (as can be seen if you click on a different panel - only that one add class event fires)
const activeClass = 'active'; const $panels = $('.panel'); let counter = 0; $panels.on('click', e => { const $panel = $(e.currentTarget); $panels.removeClass(activeClass); $panel.addClass(activeClass); }); $panels.each((index, panel) => { const observer = new MutationObserver(mutationsList => { for (let i = 0; i < mutationsList.length; i++) { if (mutationsList[i].attributeName === 'class' && mutationsList[i].target.classList.contains(activeClass)) { console.log(mutationsList[i].target.className, counter); counter++; } } }); observer.observe(panel, { attributes: true, childList: false, subtree: false }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="panel panel--1"> panel </div> <div class="panel panel--2"> panel </div> <div class="panel panel--3"> panel </div>