I'm using the below code to copy text to clipboard. The error is, it's copying even the text on the button which shouldn't happen. Can anyone explain why this is happening, and the way to prevent it?
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.10/clipboard.min.js"></script>
<code id='a'>https://www.tumblr.com/<button data-clipboard-target="#a">copy</button></code><br /><br />
<code id='b'>javascript:$('.overlay').slice(0, 100).click()<button data-clipboard-target="#b">copy</button></code><br /><br />
<script>var clipboard = new ClipboardJS('button');</script>
CodePudding user response:
If you want to use Jquery to create this function you can find a demo below!
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">Hello, I'm TEXT 1</p><button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<p id="p2">Hi, I'm the 2nd TEXT</p><br/>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
CodePudding user response:
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.10/clipboard.min.js"></script>
<code id='a'>https://www.tumblr.com/</code><button data-clipboard-target="#a">copy</button><br /><br />
<code id='b'>javascript:$('.overlay').slice(0, 100).click()</code><button data-clipboard-target="#b">copy</button><br /><br />
<script>var clipboard = new ClipboardJS('button');</script>