Skip to content

Instantly share code, notes, and snippets.

@stephenharris
Last active May 8, 2023 06:46
Show Gist options
  • Save stephenharris/25d7592f951642637e7a to your computer and use it in GitHub Desktop.
Save stephenharris/25d7592f951642637e7a to your computer and use it in GitHub Desktop.
Adding a 'copy' button to <pre> content
.pre-wrapper{
position:relative;
}
.pre-wrapper pre{
padding-top: 25px;
}
.pre-wrapper .copy-snippet {
border-radius: 0;
min-width:55px;
background: none repeat scroll 0 0 transparent;
border: 1px solid #bbb;
color: #26589F;
font-family: 'HELEVETICA',sans-serif;
font-size: 12px;
font-weight: normal;
line-height: 1.42rem;
margin: 0;
padding: 0px 5px;
text-align: center;
text-decoration: none;
text-indent: 0;
position:absolute;
background:#ccc;
top:0;
left:0;
}
.pre-wrapper .copy-snippet:disabled{
color:#555;
}
jQuery( document).ready(function($){
var copyid = 0;
$('pre').each(function(){
copyid++;
$(this).attr( 'data-copyid', copyid).wrap( '<div class="pre-wrapper"/>');
$(this).parent().css( 'margin', $(this).css( 'margin') );
$('<button class="copy-snippet">Copy</button>').insertAfter( $(this) ).data( 'copytarget',copyid );
});
$('body').on( 'click', '.copy-snippet', function(ev){
ev.preventDefault();
var $copyButton = $(this);
$pre = $(document).find('pre[data-copyid=' + $copyButton.data('copytarget' ) + ']');
if ( $pre.length ) {
var textArea = document.createElement("textarea");
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent';
//Set value to text to be copied
textArea.value = $pre.html();
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
$copyButton.text( 'Copied').prop('disabled', true);;
} catch (err) {
$copyButton.text( 'FAILED: Could not copy').prop('disabled', true);;
}
setTimeout(function(){
$copyButton.text( 'Copy').prop('disabled', false);;
}, 3000);
}
});
});
@k4mrul
Copy link

k4mrul commented May 6, 2019

Works like a magic! Thanks a lot.

@thaDev404
Copy link

Works perfectly like a charm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment