This page, or parts of it, are still untranslated. Please translate it to the appropriate language (español).
For script developers[]
Si usted usa mucho JavaScript en Fandom, se encontrará usando las mismas funciones una y otra vez. Hagamos una colección de esas funciones que copia y pega del proyecto al muro de mensajes, a la publicación del foro, al proyecto y viceversa.
Variables[]
Almacenamiento en caché de API[]
Almacena en caché una referencia a una instancia de objeto mw.Api. Para obtener más información, consulte la documentación de MediaWiki.
var api = new mw.Api();
Configuración de caché[]
Almacena en caché las variables de configuración.
var config = mw.config.get([
'wgAction',
'wgArticlePath',
'wgCanonicalSpecialPageName',
'wgPagename',
'wgTitle',
'wgSiteName'
]);
Colores[]
Determine el brillo[]
Determina si un color es brillante. Se puede utilizar para averiguar si un color de fondo o de frente es brillante u oscuro. Eso le permite elegir un color de alto contraste para el fondo o el primer plano.
Cuando se proporciona el parámetro de color en formato RGB o hexadecimal, devuelve un booleano que nos indica si el color proporcionado es brillante.
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[]
Determina el color de fondo del área del artículo y lo devuelve como una cadena con el formato de un valor de color CSS.
function getBackgroundColor() {
return getComputedStyle(document.body).getPropertyValue('--theme-page-background-color');
}
Elementos[]
Agregar un elemento HTML al contenido de la página[]
Agrega un elemento HTML al final del contenido de la página:
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.
Modals[]
Open image lightbox[]
Function to open the image lightbox for an arbitrary image programmatically, without modifying url query or reloading the page.
function openLightbox(fileName) {
const page = document.querySelector('.page');
if (!page) return;
// create a minimal lightbox trigger element
// <a class="image">
// <img data-image-key="${fileName}.png">
// </a>
const link = document.createElement('a');
link.className = 'image';
const img = document.createElement('img');
img.dataset.imageKey = fileName;
link.appendChild(img);
// note: lightbox is shown only for images inside
// the <div class="page"> element
page.appendChild(link);
// open lightbox
link.click();
// delete the trigger
page.removeChild(link);
}
The function can then be called using an image name, for example:
openLightbox('Site-logo.png');
openLightbox('Site-background-dark');
openLightbox('nonexistent.png');
Entrada[]
Caja de entrada[]
Lo siguiente agrega un cuadro de entrada al final de la página 'Página de ejemplo':
if (mw.config.get("wgPageName") === "Example_Page") {
// si la página actualmente cargada en el wiki se llama 'Example Page', este código se ejecutará
var inputBox = document.createElement("div"); // crea el elemento a div que almacenará el cuadro de entrada
var input = document.createElement("input"); // crea un elemento de entrada que obtendrá la entrada introducida
input.id = "input"; // establece la identificación del elemento de entrada en "entrada"
input.style.display = "inline-block"; // establece style.display en "inline-block" para que todo esté en una línea
var textParagraph = document.createElement("p"); // crea un párrafo de texto
textParagraph.innerHTML = "times two is: "; // establece el texto predeterminado en el párrafo
textParagraph.style.display = "inline-block"; // establece el style.display en "inline-block"
textParagraph.id = "textParagraph"; // establece el id del elemento textParagraph en "textParagraph"
var newLine = document.createElement("br"); // crea un elemento br para comenzar una nueva línea
var getAnswer = document.createElement("button"); // crea el botón de verificación
getAnswer.innerHTML = "Check"; // establece el texto del botón en "Comprobar"
getAnswer.addEventListener("click", function() {
document.getElementById("textParagraph").innerHTML= "times two is: " + document.getElementById("input").value * 2;
}); // agrega un detector de eventos al botón que establecerá el texto del elemento textParagraph en "multiplicado por dos es: (lo que sea)" cuando se hace clic en él
inputBox.appendChild(textParagraph.appendChild(input)); // agrega el elemento de entrada al cuadro de entrada
inputBox.appendChild(textParagraph); // agrega el elemento textParagraph al cuadro de entrada
inputBox.appendChild(newLine); // agrega el elemento de nueva línea al cuadro de entrada
inputBox.appendChild(getAnswer); // agrega el elemento del botón getAnswer al cuadro de entrada
document.getElementById("mw-content-text").appendChild(inputBox); // agrega el cuadro de entrada al contenido de la página principal
}
Tip: You can replace 'mw-content-text' with the ID of the desired element on the page.
Ejecución[]
Después de DOM[]
Ejecuta el código una vez que el DOM ha terminado de cargarse, utilizando una devolución de llamada lista para jQuery.
$(function() {
// código para ejecutar
});
Después de MW API[]
Ejecuta el código una vez que la biblioteca JavaScript de la API de MediaWiki ha terminado de cargarse.
mw.loader.using('mediawiki.api', function() {
// código para ejecutar
});
Después de las utilidades MW[]
Ejecuta el código una vez que la biblioteca JavaScript de las utilidades de MediaWiki ha terminado de cargarse.
mw.loader.using('mediawiki.util', function() {
// código para ejecutar
});
Después de MW API y utilidades MW[]
Ejecuta el código una vez que la API de MediaWiki y las bibliotecas de utilidades han terminado de cargarse.
mw.loader.using(['mediawiki.util', 'mediawiki.api'], function() {
// código para ejecutar
});
Después del contenido[]
Ejecuta el código cuando se agrega contenido wiki al DOM. Esto incluye el evento listo en la carga de una página (incluidas las cargas posteriores a la edición) y cuando se ha obtenido una vista previa del contenido.
mw.hook("wikipage.content").add(function($content) {
// código para ejecutar
});
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.
$('.main-container').on('mouseover', 'a.new:not([title])[href]', function() {
var regExp = /(?<=\/wiki\/)([^?]+)(?=(\?.+)?)/,
match = regExp.exec($(this).attr('href')),
title;
if (match) {
title = decodeURIComponent(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';
themeSheet1.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';
themeSheet1.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;
}
})();
Tables[]
Table progress tracking[]
This code adds a percent of checked boxes (completion percent) on every table that has progress tracking. The percent is added in the top left cell.
function percent_completed() {
// Selects all tables that have progress tracking.
const tables = document.querySelectorAll('.table-progress-tracking');
for (let i = 0; i < tables.length; i++) {
// Important for updating percentages when page loads.
observer.observe(tables[i], {
subtree: true,
childNodes: true,
attributes: true
});
var selected_boxes = 0;
var total_boxes = -1; // Omits the table header row.
for (let row of tables[i].rows) {
total_boxes += 1;
for (let cell of row.cells) {
cell.addEventListener("change", percent_completed); // On cell change, update percent.
if (cell.getAttribute('data-sort-value') == "1") {
selected_boxes += 1;
}
}
}
const th = tables[i].querySelector('th'); // Selects the first table header cell (top left).
const text = Math.round(selected_boxes / total_boxes * 100) + '%';
if (th.textContent !== text) {
th.textContent = text;
}
}
}
const observer = new MutationObserver(percent_completed);
percent_completed(); // Execute function on page load.