'Prevent multiple events using MutationObserver

I want to track a dynamic value of an input using jquery and trigger events depending on the progression (25%, 50%, 75% and 100%). In my case, the input is a progress bar: Progress bar

Here is the html code, knowing that aria-valuetext is dynamic:

<input tabindex="0" type="range" aria-hidden="false" aria-label="slide progress" aria-valuetext="30%">

To do so, I use the MutationObserver interface:

//Select the target node
const target = document.querySelector("[aria-valuetext]");
//create an observer instance
const observer = new MutationObserver(function(mutations, e){
    let videoProgress = Math.round($("[aria-valuetext]").val()/1000);
    if(videoProgression == 25){console.log('Progression:', videoProgression);
        console.log('Video action: Progression 25%');}
    if(videoProgression == 50){console.log('Progression:', videoProgression);
        console.log('Video action: Progression 50%');}
    if(videoProgression == 75){console.log('Progression:', videoProgression);
        console.log('Video action: Progression 75%');}
    if(videoProgression == 100){console.log('Progression:', videoProgression);
        console.log('Video action: Progression 100%');}
});
const config = {attributes: true, childlist: true, characterData: true};
observer.observe(target, config);

My issue is that the events are fired multiple times. I tried to use preventDefault and StopImmediatePropagation without any result.



Solution 1:[1]

Why don't you wanna track the input value using an onchange or oninput event?

MutationObserver seems a bit overkill and is intended to fire an event on every DOM mutation. You can stop observing using its .disconnect() method and start observing again using the .observe() method.

Can you add some more clarifications regarding your requirements? Which problem do you want to solve, exactly?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ˈvɔlə