You need to add a jquary to your project to make it work! For this example im using a jquary version 3.3.1 You can go and grab a new version here https://code.jquery.com/
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
- Example of html, here is a code of text and buttons
<p id="p1">Hello example 1</p>
<p id="p2">Hello ecample 2</p>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
- jQuary code
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
- You can test it here
Hello example 1
Hello ecample 2
- Full code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>clipboard</title>
</head>
<body>
<p id="p1">Hello example 1</p>
<p id="p2">Hello ecample 2</p>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
</body>
</html>