User:Gary/hide and show sidebar portlets.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.
/*
	HIDE AND SHOW SIDEBAR PORTLETS
	Description: Hides whatever sidebar portlets (the boxes to the left of every page) that are specified.
		Click on the portlet's name to expand it again.

	Usage:
		Your options are: p-navigation, p-search, p-interaction, p-tb, p-coll-print_export, p-lang
		To use, here is an example: var hidePortlet = ['p-search', 'p-lang'];
		This will hide the Search and Language boxes by default, but you can expand them when you want to.
*/

function hideAndShowSidebarPortlets()
{
	if (typeof(hidePortlet) == 'undefined' || typeof(hidePortlet) != 'object' || hidePortlet.length == 0) return false;
	
	for (i = 0; i < hidePortlet.length; i++)
	{
		var id = hidePortlet[i];
		var element = $('#' + id);
		if (!element.length) continue;
		
		if (id == 'p-search') var baseNode = element.children().eq(0).children().eq(0);
		else var baseNode = element.children().eq(0);
		
		var oldNode = baseNode.contents().eq(0);
		if (typeof(oldNode[0]) == 'undefined') break;
		
		var portletTitle = oldNode[0].nodeValue;
		var newNode = $('<a href="#" id="' + id + '" style="display: inline;">+ ' + portletTitle + '</a>').click(function(event)
		{
			event.preventDefault();
			var node = $('#' + this.id).children().eq(1);
			var currentNode = $(this).contents().get(0);
			var portletTitle = currentNode.nodeValue.substring(2);
			
			if (node.css('display') == 'block')
			{
				node.css('display', 'none');
				currentNode.nodeValue = '+ ' + portletTitle;
			}
			else
			{
				node.css('display', 'block');
				currentNode.nodeValue = '- ' + portletTitle;
			}
		});

		element.children().eq(1).css('display', 'none');
		oldNode.replaceWith(newNode);
	}
}

$(hideAndShowSidebarPortlets);