User:Darklama/preview.js

From Wikibooks, open books for an open world
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.
(function($) {
	$.fn.extend({
		preview: function(options) {
			var o = $.extend({
				speed: 100,
				opacity: 0.95,
				height: '120px',
				width: '160px',
				callback: function() {}
			}, options);

			function show() { $(this).prev().stop(true, true).fadeTo(o.speed, o.opacity); }
			function hide() { $(this).stop(true, true).fadeTo(o.speed, 0); }

			function first_time(e) {
				var $this = $(this), $self = $this.prev(), y, x, ret;

				$self.height(o.height).width(o.width);

				y = Math.floor( this.offsetHeight + $self[0].offsetHeight );
				x = Math.floor( $self.width + $this.width() / 2 );

				$self.css({
					'top': y + 'px',
					'left': x + 'px',
					'background-color': 'white',
					'padding': '5px',
					'margin': '5px',
					'overflow': 'hidden'
				});

				ret = o.callback.call( $self[0] );

				$self.bind('mouseleave.preview', hide);
				$this.unbind(e).bind('mouseenter.preview', show).trigger('mouseenter.preview');

				return ret;
			}

			return this.each( function() {
				$(this).removeAttr('title')
					.bind('mouseenter.preview', first_time)
					.before( $('<div class="preview" style="position:absolute;" />').fadeTo(1, 0) );
			});
		}
	});
})(jQuery);

mw.loader.using( 'mediawiki.util', function() {
	var BookRE = RegExp('^\/wiki\/(.*)$');

	mw.util.$content.find( 'a' ).not( '.external' ).preview({ callback: LiveBook });

	function LiveBook() {
		var $this = $(this);
		var where = BookRE.exec( $this.next().attr('href') );

		// nothing more to do
		if ( !where ) {
			return true;
		} else {
			where = where[1];
		}

		$this.html('<b>' + $this.next()[0].href + '</b>');
		return true;
	}
});