1

On a forum that I'm a member of we have a large number of threads which end up having a lot of Youtube videos embedded on, and quite a lot of people find this quite annoying when scrolling down the page. So, I would like to use Greasemonkey to wrap a spoiler each one so each video can be opened and viewed separately.

Here is code that's used for one video as an example;

<iframe src="http://www.youtube.com/embed/_IATqru7Sh8?wmode=opaque" allowfullscreen="" frameborder="0" height="300" width="500"></iframe>

And I'd like to wrap some code around it so that every video is contained in a Javascript spoiler that has a button to be clicked to show the video.

I've managed to replace simple text with Greasemonkey but this one is a bit complicated for me. Can anyone help me with this please? Thanks!

Olly88
  • 13
  • 2

1 Answers1

1

This is not too hard using the awesome power of jQuery and the waitForKeyElements utility.

  1. Use waitForKeyElements to find iframes with youtube.com in their src. waitForKeyElements is AJAX-aware.
  2. Replace each found <iframe> with a <button>, after marking the iframe as found (using the gmSpoiledAlready class in this case).
    The button also stores a copy of the iframe's source code so the the iframe can be recreated. We don't just hide the iframe, because then it could still load things in the background -- which slows the page down.
  3. Use jQuery's .on() to activate all of the buttons. When clicked, each button will replace itself with it's original iframe source.


Here's a complete Greasemonkey script:

// ==UserScript==
// @name     _Hide iframed youtube videos
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
waitForKeyElements ("iframe[src*='youtube.com']", hideYoutubeVideo);

function hideYoutubeVideo (jNode) {
    if ( ! jNode.hasClass ("gmSpoiledAlready") ) {
        jNode.addClass ("gmSpoiledAlready");

        var srcCode     = jNode[0].outerHTML;

        jNode.after ('<button class="gmYT_hide">Show YouTube video</button>');
        jNode.next ('button').data ("frmCode", srcCode);
        jNode.remove ();
    }
}

//--- Activate any and all of the spoiler buttons
$(document.body).on ("click", "button.gmYT_hide", restoreYoutubeVideo)

function restoreYoutubeVideo (evnt) {
    var jThis   = $(evnt.target);
    var frmCode = jThis.data ("frmCode");

    jThis.replaceWith (frmCode);
}
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295