Jump to content

User:Jackmcbarn/switcher-unstable.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.
'use strict';
$( function () {
	$.each( document.querySelectorAll( '.switcher-container' ), function ( i ) {
		var activeElement,
			switchers = [], showLabels = [], container = this, radioName = 'switcher-' + i,
			labelStyle = $( this ).attr( 'data-switcher-label-style' );
		if ( labelStyle === undefined ) {
			labelStyle = 'display:block';
		}
		$.each( this.children, function () {
			var $radio, switcher = this,
				$labelContainer = $( switcher.querySelector('.switcher-label') ),
				$labelText = $labelContainer.contents();
			if ( !$labelText.length ) {
				return;
			}
			switchers.push( switcher );
			$radio = $( '<input type="radio">' ).attr( 'name', radioName ).click( function () {
				$( activeElement ).hide();
				$( switcher ).show();
				activeElement = switcher;
			} );
			if ( !activeElement ) {
				// Mark the first one as selected
				activeElement = switcher;
				$radio.prop( 'checked', true );
			} else if ( $labelContainer.attr( 'data-switcher-default' ) !== undefined ) {
				// Custom default
				$radio.click();
			} else {
				// Hide non-default
				$( switcher ).hide();
			}
			showLabels.push( $( '<label></label>' ).attr( 'style', labelStyle ).append( $radio, $labelText ) );
			$labelContainer.remove();
		} );
		if ( switchers.length > 1 ) {
			showLabels.push( $( '<label>Show all</label>' ).attr( 'style', labelStyle ).prepend(
				$( '<input type="radio">' ).attr( 'name', radioName ).click( function () {
					$( switchers ).show();
					activeElement = switchers;
				} )
			) );
			if ( $( this ).attr( 'data-switcher-top-choices' ) !== undefined ) {
				$( container ).prepend( showLabels );
			} else {
				$( container ).append( showLabels );
			}
		}
		if ( switchers.length === 1 ) {
			$radio.remove();
		}
	} );
} );