I am trying to copy the current page URL in the text area on button click. Somehow I have tried but is not working. http://www.w3schools.com/code/tryit.asp?filename=FAF25LWI
<html>
<head>
<title></title>
</head>
<script type="text/javascript">
function Copy()
{
//var Url = document.createElement("textarea");
urlCopied.innerHTML = window.location.href;
//Copied = Url.createTextRange();
//Copied.execCommand("Copy");
}
</script>
<body>
<div>
<input type="button" value="Copy Url" onclick="Copy();" />
<br />
Paste: <textarea id="urlCopied" rows="1" cols="30"></textarea>
</div>
</body>
</html>
When the button is clicked select the content of #url then copy it to the clipboard.
<html>
<body>
<input type="button" value="Copy Url" id="copy" />
<br />
Paste: <textarea rows="1" cols="30" id="url"></textarea>
<script type="text/javascript">
document.querySelector("#copy").onclick = function() {
document.querySelector("#url").select();
document.execCommand('copy');
};
</script>
</body>
</html>
Another solution, no extra html
code is needed:
<script>
$(document).ready(function () {
$(document).on("click", "#ShareButton", function (e) {
$("body").append('<input id="copyURL" type="text" value="" />');
$("#copyURL").val(window.location.href).select();
document.execCommand("copy");
$("#copyURL").remove();
});
});
</script>
Modified your code little bit and it's working.
<html>
<head>
<title></title>
</head>
<script type="text/javascript">
function Copy()
{
var Url = document.getElementById("paste-box");
Url.value = window.location.href;
Url.focus();
Url.select();
document.execCommand("Copy");
}
</script>
<body>
<div>
<input type="button" value="Copy Url" onclick="Copy();" />
<br />
Paste: <textarea id="paste-box" rows="1" cols="30"></textarea>
</div>
</body>
</html>
No need to create new textarea
. try to get existing textarea
by giving some id
('url').
Here is the working example
function Copy() {
var Url = document.getElementById("url");
Url.innerHTML = window.location.href;
console.log(Url.innerHTML)
Url.select();
document.execCommand("copy");
}
<div>
<input type="button" value="Copy Url" onclick="Copy();" />
<br /> Paste: <textarea id="url" rows="1" cols="30"></textarea>
</div>