Fandom Developers Wiki
Advertisement

For script developers

If you use JavaScript on Fandom a lot, you'll find yourself using the same functions again and again. Let's make a collection of those functions you copy-paste from project to message wall to forum post to project and back.

Variables

Caching API

Caches a reference to an mw.Api object instance. For more info, see MediaWiki documentation.

var api = new mw.Api();

Caching configuration

Caches configuration variables.

var config = mw.config.get([
    'wgAction',
    'wgArticlePath',
    'wgCanonicalSpecialPageName',
    'wgPagename',
    'wgTitle',
    'wgSiteName'
]);

Colors

Determine brightness

Determines whether a color is bright. Can be used to find out if a fore or background color is bright or dark. That enables you to pick a high-contrast color for back- or foreground.

When supplied the color parameter in a RGB or hexadecimal format returns a boolean representing whether the supplied color is bright.

function isBright(color) {
    var m = color.match(/(?:([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2}))|(?:(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3}))/);
    if (!m) return false;
    var rgb = m[1] ? { r: parseInt(m[1], 16), g: parseInt(m[2], 16), b: parseInt(m[3], 16) }
                   : { r: parseInt(m[4], 10), g: parseInt(m[5], 10), b: parseInt(m[6], 10) };
    return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000 >= 128;
}

Get background color

Determines the article area's background color and returns it as a string in the format of a CSS color value.

function getBackgroundColor() {
    return getComputedStyle(document.body).getPropertyValue('--theme-page-background-color');
}

Elements

Add an HTML element to the page content

Adds a HTML element to the end of the page content:

var element = document.createElement("p"); // "p" is the type of element that will be created
element.style = "color:blue"; // to modify attributes to the element that will be created, just type element.(attribute you want to modify) = "whatever value"
element.contentText = "Paragraph text"; // this sets the innerHTML of the element that will be created to "Paragraph text"
document.getElementById('mw-content-text').appendChild(element); // this adds the element to the page content

Tip: You can replace 'mw-content-text' with the ID of the desired element on the page.

Input

Input box

The following adds a input box to the end of the page 'Example Page':

if (mw.config.get("wgPageName") === "Example_Page") {
  // if the page currently loaded on the wiki is named 'Example Page' this code will be ran
  var inputBox = document.createElement("div"); // create the a div element that will store the input box
  var input = document.createElement("input"); // create a "input" element that will get the input entered
  input.id = "input"; // set the id to the input element to "input"
  input.style.display = "inline-block"; // set the style.display to "inline-block" so it will all be in one line
  var textParagraph = document.createElement("p"); // create a text paragraph
  textParagraph.innerHTML = "times two is: "; // set the default text to the paragraph
  textParagraph.style.display = "inline-block"; // set the style.display to "inline-block" so it will all be in one line
  textParagraph.id = "textParagraph"; // set the id to the textParagraph element to "textParagraph"
  var newLine = document.createElement("br"); // create a br element to start a new line
  var getAnswer = document.createElement("button"); // create the check button
  getAnswer.innerHTML = "Check"; // set the text on the button to "Check"
  getAnswer.addEventListener("click", function() {
    document.getElementById("textParagraph").innerHTML= "times two is: " + document.getElementById("input").value * 2;
  }); // add an event listener to the button that will set the text to the textParagraph element to "times two is: (whatever it is)" when it is clicked
  inputBox.appendChild(textParagraph.appendChild(input)); // add the input element to the input box
  inputBox.appendChild(textParagraph); // add the textParagraph element to the input box
  inputBox.appendChild(newLine); // add the new line element to the input box
  inputBox.appendChild(getAnswer); // add the getAnswer button element to the input box
  document.getElementById("mw-content-text").appendChild(inputBox); // add the input box to the main page content
}

Tip: You can replace 'mw-content-text' with the ID of the desired element on the page.

Execution

After DOM

Runs the code once the DOM has finished loading, using a jQuery ready callback.

$(function() {
    // code to run
});

After MW API

Runs the code once the MediaWiki API JavaScript library has finished loading.

mw.loader.using('mediawiki.api', function() {
    // code to run
});

After MW utilities

Runs the code once the MediaWiki utilities JavaScript library has finished loading.

mw.loader.using('mediawiki.util', function() {
    // code to run
});

After MW API and utilities

Runs the code once the MediaWiki API and Utilities libraries have finished loading.

mw.loader.using(['mediawiki.util', 'mediawiki.api'], function() {
    // code to run
});

After content

Runs the code when wiki content is being added to the DOM. This includes the ready event on a page load (including post-edit loads) and when content has been previewed.

mw.hook("wikipage.content").add(function($content) {
    // code to run
});

For users

Adding target titles to redlinks

Wiki links have a their target page stored in the title attribute, which on many browsers is displayed as a tooltip when hovering over the link. The following snippet (by HumansCanWinElves) adds such titles to redlinks too.

mw.loader.using('mediawiki.Uri').then(function() {
    $('.main-container').on('mouseover', 'a.new:not([title])[href]', function() {
        var regExp = /(?<=\/wiki\/)([^?]+)(?=(\?.+)?)/,
            match = regExp.exec($(this).attr('href')),
            title;

        if (match) {
            title = mw.Uri.decode(match[0]).replace(/_/g, ' ');
            $(this).attr('title', title);
        }
    });   
});

Using a different theme for a certain wiki

Special:Preferences allows choosing between light or dark theme, but the selection is network-wide, with the only dynamic option to defer to the theme defined as the default one by the admins of each wiki. Sometimes you want to use different themes for different wikis based on your own choosing.

Some notes:

  • This should have been mostly possible by just CSS, if the built-in theme stylesheets weren't being weirdly added below the user stylesheets. As it is now, JavaScript is required, with the cost of a little delay on each page load when the default theme is displayed until the new theme takes over.
  • The script ThemeSelector already allows presetting a theme for a certain wiki, but the need to import the script makes the delay longer and therefore more annoying, so putting some code directly on your JS page may be preferrable.
  • As other customizations, it wouldn't work on the Discussions area.

To switch to dark theme on a certain wiki, add the following code to your local personal Special:Mypage/common.js page on that wiki (expand to see the code):

(function setDarkTheme() {
	var themeSheet1 = document.createElement('link'),
	    themeSheet2 = document.createElement('link');

    themeSheet1.rel = 'stylesheet';
    themeSheet2.href = '/wikia.php?controller=ThemeApi&method=themeVariables&variant=dark';

    themeSheet2.rel = 'stylesheet';
    themeSheet2.href = '/load.php?fandomdesktop=1&lang=en&modules=' +
	    	'ext.fandom.GlobalComponents.GlobalComponentsTheme.dark.css%7C' +
	    	'ext.fandom.GlobalComponents.GlobalNavigationTheme.dark.css' +
	    	'&only=styles&skin=fandomdesktop';

	document.head.appendChild(themeSheet1);
	document.head.appendChild(themeSheet2);

	document.body.classList.remove('theme-fandomdesktop-light');
	document.body.classList.add('theme-fandomdesktop-dark');
	mw.config.set('isDarkTheme', true);
})();

To switch to light theme on a certain wiki, add the following code to your local personal Special:Mypage/common.js page on that wiki (expand to see the code):

(function setLightTheme() {
	var themeSheet1 = document.createElement('link'),
	    themeSheet2 = document.createElement('link');

    themeSheet1.rel = 'stylesheet';
    themeSheet2.href = '/wikia.php?controller=ThemeApi&method=themeVariables&variant=light';

    themeSheet2.rel = 'stylesheet';
    themeSheet2.href = '/load.php?fandomdesktop=1&lang=en&modules=' +
	    	'ext.fandom.GlobalComponents.GlobalComponentsTheme.light.css%7C' +
	    	'ext.fandom.GlobalComponents.GlobalNavigationTheme.light.css' +
	    	'&only=styles&skin=fandomdesktop';

	document.head.appendChild(themeSheet1);
	document.head.appendChild(themeSheet2);

	document.body.classList.remove('theme-fandomdesktop-dark');
	document.body.classList.add('theme-fandomdesktop-light');
	mw.config.set('isDarkTheme', false);
})();

Alternatively, add the following code to your global JS page and put the wikis you want to change the theme for in the lines that begin with case:, replacing the example wikis (expand to see the code):

(function setTheme() {
	var themeSheet1 = document.createElement('link'),
	    themeURL1 = '/wikia.php?controller=ThemeApi&method=themeVariables&variant=',
	    themeSheet2 = document.createElement('link'),
	    themeURL2 = '/load.php?fandomdesktop=1&lang=en&modules=' +
	    	'ext.fandom.GlobalComponents.GlobalComponentsTheme.$1.css%7C' +
	    	'ext.fandom.GlobalComponents.GlobalNavigationTheme.$1.css' +
	    	'&only=styles&skin=fandomdesktop';
	
	switch (mw.config.get('wgServerName')) {
		// Wikis to switch to dark mode
		case 'community.fandom.com':
		case 'dev.fandom.com':
		case 'math.wikia.org':
			themeSheet1.rel = "stylesheet";
			themeSheet1.href = themeURL1 + 'dark';
			document.head.appendChild(themeSheet1);

			themeSheet2.rel = "stylesheet";
			themeSheet2.href = themeURL2.replace(/\$1/g, 'dark');
			document.head.appendChild(themeSheet2);

			document.body.classList.remove('theme-fandomdesktop-light');
			document.body.classList.add('theme-fandomdesktop-dark');
			mw.config.set('isDarkTheme', true);
			break;

		// Wikis to switch to light mode
		case 'wreckit-woodhouse.fandom.com':
		case 'harrypotter.fandom.com':
			themeSheet1.rel = "stylesheet";
			themeSheet1.href = themeURL1 + 'light';
			document.head.appendChild(themeSheet1);

			themeSheet2.rel = "stylesheet";
			themeSheet2.href = themeURL2.replace(/\$1/g, 'light');
			document.head.appendChild(themeSheet2);

			document.body.classList.remove('theme-fandomdesktop-dark');
			document.body.classList.add('theme-fandomdesktop-light');
			mw.config.set('isDarkTheme', false);
			break;
	}
})();
Text above can be found here (edit)
Advertisement