User:Betty/custom languages.js

/** * display a collapse/expand button next to each language * all languages are collapsed by default * you can toggle each language and your preference will be remembered * by User:Betty */ (function ( $, mw ) {

'use strict';

$(document).ready(function{		init;	});

function init{ // only work on content pages, e.g., not special pages if (mw.config.get('wgNamespaceNumber') !== 0){ return; }

// find the region of each language find_region;

// set up click event for the toggle button watch_button;

// auto collapse all regions on page load auto_collapse; }

// find the region of each language function find_region{ var titles = $('h2').has('.mw-headline'); titles.each(function(i) {			// the region is all the elements between this title and next title			// for the last language, it's all the elements after the title			if (i < titles.length-1) {				var region = $(this).nextUntil(titles[i+1]);			} else {				var region = $(this).nextAll;			}

// wrap the region var lang = $(this).children('.mw-headline').attr('id'); region.wrapAll('');

// display the toggle button $(this).append('Collapse ▲');

});

}

// click the button to toggle function watch_button{ $('.bettycl-toggle').click(function {			// get the language from the class name			var langclass = $(this).attr('class').replace('bettycl-toggle ', '');

// toggle the region accordingly $('.bettycl-region.'+langclass).toggle;

// change the text on the button accordingly, and save the setting in localStorage if ($(this).text === 'Collapse ▲') { $(this).text('Expand ▼'); save_setting(langclass, 'collapse'); } else { $(this).text('Collapse ▲'); save_setting(langclass, 'expand'); }

});	}

/**	 * save the setting in localStorage * @param langclass {string} lang code * @param action {string} 'expand' or 'collapse' */	function save_setting(langclass, action){ // first read what is already there var list = JSON.parse(localStorage.getItem('bettycl-langs')); if (list == null) { list = {}; }		if (action === 'expand') { list[langclass]= 1; } else if (action === 'collapse') { list[langclass]= 0; }

localStorage.setItem('bettycl-langs', JSON.stringify(list)); }

// auto collapse on page load function auto_collapse{ // read the setting from localStorage var lang_list = JSON.parse(localStorage.getItem('bettycl-langs')); if (lang_list == null) { lang_list = {}; }

// collpase regions according to the setting var button_list = $('.bettycl-toggle'); button_list.each(function {			// get the language from the class name			var langclass = $(this).attr('class').replace('bettycl-toggle ', '');

// if a language is not on the list or is recorded as collapsed, it will be auto collapsed if (lang_list[langclass] === undefined || (lang_list[langclass] === 0)) { $(this).click; }

});

}

})( window.jQuery, mediaWiki );