Tiggles ツ of Speak Creative
10/22/2019 - 2:15 PM

Media PP Mutation Observer

The Media PP reshuffles the DOM asynchronously when user plays w it. Using a Mutation Observer (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver), this script will detect DOM changes, and run a function to shuffle ur HTML in a way that we want. ie http://cloud.madebyspeak.com/cb9c0e

$(document).ready(function() {

  if ($("body.watch").length) {

    function styleIT() {
      if (!$("#detail-side").length) {
        var coverImg = $(".episode-details img"),
            socialStuff = $(".episode-details .sharing, .episode-details .subscribe"),
            mainDetails = $(".episode-details .main-details, .episode-details .sharing, .episode-details .subscribe, .episode-details .metadata"),
            $podButts = $('.sw-media-archive-series-podcast .sw-media-archive-episode-button, .sw-media-archive-channel-podcast .sw-media-archive-episode-button');

        $(coverImg).wrap("<div id='image-side' />");
        $(mainDetails).wrapAll("<div id='detail-side' />");
        $(socialStuff).wrapAll("<div class='follow' />")

        $("#image-side").css("background-image", "url("+$("#image-side").find("img").attr("src")+")");

        // remove floating text (have to elem check bc it loads later in DOM)
        function checkForItem(elementName) {
          if ($(elementName).length >= 1) {
            clearInterval(elementChecker);
            $podButts.html($podButts.html().replace(/([\s\S]*a\>)[\s\S]*/gi, '$1'));
          }
        }
        var elementChecker = setInterval(function() {
          checkForItem(".sw-media-archive-episode-button");
        }, 500);
      }
      if ($(".episode-details > .embed").length) {
        $(".episode-details > .embed").wrap("<div id='image-side' />");
      }
    }
    styleIT();
    // Select the node that will be observed for mutations
    var targetNode = document.querySelector('.sw-media-archive');
    var config = { 
      attributes: true, 
      childList: true, 
      subtree: true 
    };

    // Callback function to execute when mutations are observed
    const callback = function(mutationsList, observer) {
        for(var mutation of mutationsList) {
            if (mutation.type === 'attributes') {
              styleIT();
            }
        }
    };

    // 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);


  }
 
});