Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Alternative to DOMSubtreeModified

I have the following Javascript/Jquery code:

       <script type="text/javascript">
            function ChangeMathOnPage() {
                MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
            }

            $('.markdownx-preview').each(function(){
                $(this).on('DOMSubtreeModified', ChangeMathOnPage);
            });
        </script>

This does my job. However, as explained here, use of DOMSubtreeModified is deprecated.

To somebody new to Javascript/Jquery world, please explain ways to convert same logic into non-deprecated code.

like image 424
inquilabee Avatar asked Oct 21 '25 05:10

inquilabee


1 Answers

Try this:

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Source: MDN: MutationObserver

like image 75
awran5 Avatar answered Oct 23 '25 18:10

awran5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!