Jump to content

MediaWiki:Gadget-switcher.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Krinkle (talk | contribs) at 03:01, 18 September 2019 (Maintenance: Various optimisations - fewer DOM/jQuery operations, less Sizzle selector overhead, avoid post-append mutation). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
'use strict';
$( function () {
	$.each( document.querySelectorAll( '.switcher-container' ), function ( i ) {
		var activeElement, $showAllRadio;
		var switchers = [], container = this, radioName = 'switcher-' + i;
		$.each( this.children, function () {
			var switcher = this, $showRadio;
			var $labelContainer = $( switcher ).find( '.switcher-label' );
			var $labelText = $labelContainer.contents();
			if ( !$labelText.length ) {
				return;
			}
			switchers.push( switcher );
			$showRadio = $( '<input type="radio">' ).attr( 'name', radioName ).click( function () {
				$( activeElement ).hide();
				$( switcher ).show();
				activeElement = switcher;
			} );
			if ( !activeElement ) {
				activeElement = switcher;
				$showRadio.prop( 'checked', true );
			} else if ( $labelContainer.attr( 'data-switcher-default' ) !== undefined ) {
				$showRadio.click();
			} else {
				$( switcher ).hide();
			}
			$( '<label style="display:block"></label>' ).append( $showRadio, $labelText ).appendTo( container );
			$labelContainer.remove();
		} );
		if ( switchers.length > 1 ) {
			$showAllRadio = $( '<input type="radio">' ).attr( 'name', radioName ).click( function () {
				$( switchers ).show();
				activeElement = switchers;
			} );
			$( '<label style="display:block">Show all</label>' ).prepend( $showAllRadio ).appendTo( container );
		}
		if ( switchers.length === 1 ) {
			$showRadio.remove();
		}
	} );
} );