Jump to content

User:Awesome Aasim/copycodeblock.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Awesome Aasim (talk | contribs) at 03:42, 19 August 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
(function copyCodeBlock() {
	$(document).ready(function() {
		let $pres = $("#mw-content-text").find('pre').not('form *');
		if (!$pres.length) return;
		mw.loader.addStyleTag('.copycodeblock-block{position:relative} .copycodeblock{position:absolute;top:0;right:0} :not(:hover) > .copycodeblock:not(:focus-within){opacity:0}');
		mw.loader.using(['oojs-ui-core', 'oojs-ui.styles.icons-editing-advanced'], function() {
			$pres.each(function() {
				let $pre = $(this);
				let button = new OO.ui.ButtonWidget({
					classes: ['copycodeblock'],
					framed: false,
					icon: 'copy',
					title: 'Copy to clipboard',
				});
				button.$element.click(() => {
					var value = $pre.text();
					var $temp = $("<textarea>");
					$("body").append($temp);
					$temp.val(value).select();
					document.execCommand("copy");
					$temp.remove();
					button.icon = 'checkAll';
					window.setTimeout(function() {
						button.icon = 'check';
					}, 3000);
				});
				$pre.addClass('copycodeblock-block').append(button.$element);
			})
		});
	});
}());