Difference between revisions of "MediaWiki:Common.js"
From Bharatpedia
(Created page with "→Any JavaScript here will be loaded for all users on every page load.: →Any JavaScript here will be loaded for all users on every page load.: console.clear() const wikiUrl = 'https://en.bharatpedia.org' const params = 'action=query&list=search&format=json&origin=*' new Autocomplete('#autocomplete', { // Search function can return a promise // which resolves with an array of // results. In this case we're using // the bharatpedia search API. search:...") |
|||
Line 1: | Line 1: | ||
/* Any JavaScript here will be loaded for all users on every page load. */ | /* Any JavaScript here will be loaded for all users on every page load. */ | ||
/ | $(function () { | ||
var myElement = document.getElementById('search-box'); | |||
myElement.innerHTML = '<div id="autocomplete" class="autocomplete"> | |||
<input class="autocomplete-input" placeholder="Search Bharatpedia" aria-label="Search Bharatpedia"/> | |||
<ul class="autocomplete-result-list"></ul> | |||
</div>'; | |||
}()); | |||
console.clear() | console.clear() | ||
Latest revision as of 21:29, 26 August 2022
/* Any JavaScript here will be loaded for all users on every page load. */ $(function () { var myElement = document.getElementById('search-box'); myElement.innerHTML = '<div id="autocomplete" class="autocomplete"> <input class="autocomplete-input" placeholder="Search Bharatpedia" aria-label="Search Bharatpedia"/> <ul class="autocomplete-result-list"></ul> </div>'; }()); console.clear() const wikiUrl = 'https://en.bharatpedia.org' const params = 'action=query&list=search&format=json&origin=*' new Autocomplete('#autocomplete', { // Search function can return a promise // which resolves with an array of // results. In this case we're using // the bharatpedia search API. search: input => { const url = `${wikiUrl}/api.php?${ params }&srsearch=${encodeURI(input)}` return new Promise(resolve => { if (input.length < 3) { return resolve([]) } fetch(url) .then(response => response.json()) .then(data => { const results = data.query.search.map((result, index) => { return { ...result, index } }) resolve(results) }) }) }, // Control the rendering of result items. // Let's show the title and snippet // from the bharatpedia results renderResult: (result, props) => { let group = '' if (result.index % 3 === 0) { group = `<li class="group">Group</li>` } return ` ${group} <li ${props}> <div class="wiki-title"> ${result.title} </div> <div class="wiki-snippet"> ${result.snippet} </div> </li> ` }, // bharatpedia returns a format like this: // // { // pageid: 12345, // title: 'Article title', // ... // } // // We want to display the title getResultValue: result => result.title, // Open the selected article in // a new window onSubmit: result => { window.open(`${wikiUrl}/wiki/${ encodeURI(result.title) }`) } })