MediaWiki:Common.js/RandomBook.js
Jump to navigation
Jump to search
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
- Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac);
- Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5;
- Konqueror: simply click the Reload button, or press F5;
- Opera users may need to completely clear their cache in Tools→Preferences.
This is JavaScript for all users. You can propose changes on the discussion page or at the proposals reading room. Errors made here can disrupt Wikibooks. You can test changes in your personal JavaScript first. Due to caching, changes can take up to 31 days before propagating to all users. |
/* Random Book Finder, version [0.0.4a-r3]
Originally from: http://en.wikibooks.org/wiki/User:Splarka/randbook.js
Based roughly on http://en.wikibooks.org/w/index.php?title=MediaWiki:RandomBook.js&oldid=1209572 by Darklama.
Notes:
* Grab only 10 random pages in one go because that is the limit.
* 2 iterations may be needed because 10.5% of pages are books.
* Refer to books by their ID to find them even when moved.
* Append links instead with: mw.config.set( 'random_book_list', true ); (add this in your [[Special:MyPage/common.js]]);
*/
$(document).ready( function($) {
var reqid = 0, random_list = mw.config.get( 'random_book_list', false ),
randbookLink = mw.util.addPortletLink( 'p-navigation', '#', 'Random book', 'n-randbook', 'Show me a random book', 'x' ),
bookLink = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?curid=';
function fetch_categories( id, callback ) {
$.getJSON( mw.util.wikiScript( 'api' ), {
format: 'json',
action: 'query',
prop: 'categories',
cllimit: 100,
generator: 'random',
grnnamespace: '0|110',
grnlimit: 10,
requestid: id
}, callback );
}
function showRandBookCB(obj) {
var pages;
if ( !obj.query || !obj.query.pages ) {
$(randbookLink).append('<span class="error">error</span>');
if ( random_list ) {
removeSpinner( 'randbook' );
}
return;
}
pages = $.map( obj.query.pages, function(page, id) {
return $.map( page.categories || [], function( cat ) {
if ( cat.title.indexOf( 'Category:Alphabetical/' ) === 0 ) {
return { id: id, title: page.title };
}
});
});
if ( !pages.length ) {
// didn't find any, try again
++reqid;
fetch_categories( reqid, showRandBookCB );
return;
}
if ( !random_list ) {
window.location.assign( bookLink + pages[ Math.floor( Math.random()*pages.length ) ].id );
return;
}
removeSpinner( 'randbook' );
$.each( pages, function() {
$(randbookLink).append('<div><a href="' + bookLink + this.id + '"> \u2022\u00A0' + this.title + '</a></div>');
});
}
$(randbookLink).click( function(e) {
if ( random_list ) {
injectSpinner( this, 'randbook' );
}
++reqid;
fetch_categories( reqid, showRandBookCB );
e.preventDefault();
});
});