MediaWiki:Common.js
From zunagi
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */
$( function () {
const input = document.getElementById( 'zunagi-search-input' );
const box = document.getElementById( 'zunagi-search-suggestions' );
if ( !input || !box ) {
return;
}
let timer = null;
let requestNumber = 0;
function closeSuggestions() {
box.innerHTML = '';
box.classList.remove( 'is-open' );
}
function openArticle( title ) {
window.location.href = mw.util.getUrl( title );
}
function showSuggestions( titles ) {
box.innerHTML = '';
if ( !titles.length ) {
closeSuggestions();
return;
}
titles.forEach( function ( title ) {
const link = document.createElement( 'a' );
link.href = mw.util.getUrl( title );
link.className = 'zunagi-search-suggestion';
link.textContent = title;
link.addEventListener( 'mousedown', function ( event ) {
event.preventDefault();
openArticle( title );
} );
box.appendChild( link );
} );
box.classList.add( 'is-open' );
}
input.setAttribute( 'autocomplete', 'off' );
input.addEventListener( 'input', function () {
const query = input.value.trim();
clearTimeout( timer );
if ( query.length < 2 ) {
closeSuggestions();
return;
}
timer = setTimeout( function () {
const thisRequest = ++requestNumber;
new mw.Api().get( {
action: 'opensearch',
search: query,
namespace: 0,
limit: 8,
format: 'json'
} ).done( function ( data ) {
if ( thisRequest !== requestNumber ) {
return;
}
showSuggestions( data[ 1 ] || [] );
} ).fail( closeSuggestions );
}, 250 );
} );
input.addEventListener( 'keydown', function ( event ) {
if ( event.key === 'Escape' ) {
closeSuggestions();
}
} );
document.addEventListener( 'click', function ( event ) {
if (
event.target !== input &&
!box.contains( event.target )
) {
closeSuggestions();
}
} );
} );