Referencing MDN Web Docs
The HTMLInputElement.select() function is designed to highlight all text within an input field or textarea field.
This signifies that the .select() method will not function properly on elements other than input and textarea. In a scenario where I have content within code and pre tags that I want users to be able to copy by clicking on a copy button, this limitation poses a challenge.
$(document).ready(function() {
$('code, pre').append('<span class="command-copy" ><i class="fa fa-clipboard" aria-hidden="true"></i></span>');
$('code span.command-copy').click(function(e) {
text = $(this).parent().select(); //.text();
copiedText = $.trim(text);
document.execCommand("copy");
});
$('pre span.command-copy').click(function(e) {
text = $(this).parent().parent().select(); //.text();
copiedText = $.trim(text);
document.execCommand("copy");
});
})
code,
pre {
position: relative;
}
code,
pre {
display: block;
padding: 20px;
background: #f2f2f2;
color: #555755;
}
span.command-copy {
position: absolute;
top: 10px;
right: 10px;
opacity: .6;
font-size: 20px;
color: #555755;
}
span.command-copy:hover {
cursor: pointer;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h4>
<b>Steps to install pytest</b>
</h4>
<p>
<b>Step 1: </b>Open the terminal and type in this command:
</p>
<code class="command-copy">
pip install pytest
</code>
<p>Or you can upgrade your existing:
<p>
<pre><span></span><span class="nv">pip</span> install --upgrade pytest
<span class="command-copy"><i class="fa fa-clipboard" aria-hidden="true"></i></span></pre>
Is there a workaround for this issue? Thank you