Jump to content

User:Cryptic/spoiler.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<pre><nowiki>
var hide_spoilers_initially = window.hide_spoilers_initially || false;
var hide_endspoiler_tag = window.hide_endspoiler_tag || false;
var spoiler_num = 0;

function spoiler_toggle(num)
{
  var contents = document.getElementById('spoilercontents_' + num);
  var lk = document.getElementById('spoilerlk_' + num);
  if (!contents || !lk)
    return;
  if (contents.style.display == 'none')
    {
      contents.style.display = '';
      lk.replaceChild(document.createTextNode('hide'), lk.firstChild);
    }
  else
    {
      contents.style.display = 'none';
      lk.replaceChild(document.createTextNode('show'), lk.firstChild);
    }
}

function setup_spoilers()
{
  var divs = document.getElementsByTagName('div');
  var hide_initially = hide_spoilers_initially
                       && !/(\?title=|\/wiki\/)(Talk|User|Wikipedia|Image|MediaWiki|Template|Help|Category|Portal)(_talk)?:/.test(window.location.href);

  for (var i = 0; i < divs.length; ++i)
    {
      var node = divs[i];
      if (node.id != 'spoiler')
        continue;

      ++spoiler_num;

      var lk = document.createElement('a');
      lk.setAttribute('href', 'javascript:spoiler_toggle(' + spoiler_num + ')');
      lk.appendChild(document.createTextNode(hide_initially ? 'show' : 'hide'));
      lk.id = 'spoilerlk_' + spoiler_num;
      lk.className = 'spoilertoggle';

      node.appendChild(document.createTextNode(' ['));
      node.appendChild(lk);
      node.appendChild(document.createTextNode(']'));

      var contents = document.createElement('div');
      contents.className = 'spoilercontents';
      contents.id = 'spoilercontents_' + spoiler_num;
      if (hide_initially)
        contents.style.display = 'none';

      var depth = 0;
      while (depth >= 0)
        {
          var n = node.nextSibling;
          if (!n)
            break;

          if (n.id == 'spoiler')
            ++depth;
          else if (n.className && n.className.indexOf('endspoiler') >= 0
                   && --depth < 0 && !hide_endspoiler_tag)
            break;

          n.parentNode.removeChild(n);
          contents.appendChild(n);
        }

      if (node.nextSibling)
        node.parentNode.insertBefore(contents, node.nextSibling);
      else
        node.parentNode.appendChild(contents);
    }
}

addOnloadHook(setup_spoilers);
//</nowiki></pre>