User:Erutuon/scripts/vsSwitcher.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

function viewSwitching($rootElement) {
	var showButtonText = $rootElement.data("vs-showtext") || "more ▼";
	var hideButtonText = $rootElement.data("vs-hidetext") || "less ▲";
	
	var toSkip = $rootElement.find(".newVsSwitcher").find("*");
	var allElemsToHide = $rootElement.find(".newVsHide").not(toSkip);
	var allElemsToShow = $rootElement.find(".newVsShow").not(toSkip);

	// Determine the visibility toggle category (for the links in the bar on the left).
	var toggleCategory = $rootElement.data("toggle-category");
	if (!toggleCategory) {
		var classNames = $rootElement.attr("class").split(/\s+/);

		for (var i = 0; i < classNames.length; ++i) {
			var className = classNames[i].split("-");

			if (className[0] == "newVsToggleCategory") {
				toggleCategory = className[1];
			}
		}
	}

	if (!toggleCategory)
		toggleCategory = "others";
	
	// Find the element to place the toggle button in.
	$rootElement.find(".newVsToggleElement").not(toSkip).each(function (i, elem) {
		$this = $(this);
		
		// The toggleElement becomes clickable in its entirety, but
		// we need to prevent this if a contained link is clicked instead.
		$this.children("a").on("click", function (e) {
			e.stopPropagation();
		});

		// Add the toggle button.
		var toggleButton = $("<a>");

		$("<span>").addClass("NavToggle").append(toggleButton).prependTo($this);
		
		var elemsToShow = allElemsToShow;
		var elemsToHide = allElemsToHide;
		
		var subtoggle = $this.data("vs-subtoggle");
		
		if (subtoggle) {
			elemsToShow = elemsToShow.filter(function (i, elem) { return $(elem).data("vs-subtoggle") == subtoggle; });
			elemsToHide = elemsToHide.filter(function (i, elem) { return $(elem).data("vs-subtoggle") == subtoggle; });
		}

		// Register the visibility toggle.
		$this.css("cursor", "pointer");
		$this.on("click", window.VisibilityToggles.register(toggleCategory,
			function show() {
				toggleButton.html(hideButtonText);
				elemsToShow.hide();
				elemsToHide.show();
			},
			function hide() {
				toggleButton.html(showButtonText);
				elemsToShow.show();
				elemsToHide.hide();
			}));
	});
}

$(function () {
	$(".newVsSwitcher").each(function (i, elem) {
		viewSwitching($(elem));
	});
});