Hey coders, today let's see how to copy text to clipboard in your website using JavaScript. Before we dive in, do check out our video tutorial of this below:
Okay, so first we'll see what and how this project works. When the user clicks the copy text button, it will copy some text that we already set to the user's clipboard. This is very handy to use to let your users copy long links or long blocks of code.
So for this project, copy and paste the code below in your index.html file:
<!-- Created by CodingPorium,2021. Visit https://youtube.com/c/CodingPorium for more tutorials with free source code -->
<!DOCTYPE html>
<html>
<title>Copy to Clipboard Using JavaScript | CodingPorium</title>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
::selection{
color:black;
background:gold;
}
body {
display: flex;
font-family:poppins;
justify-content: center;
align-items: center;
background-color:tomato;
height: 600px;
}
.container{
background: rgba( 255, 255, 255, 0.25 );
box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
backdrop-filter: blur( 4px );
-webkit-backdrop-filter: blur( 4px );
border-radius: 10px;
border: 1px solid rgba( 255, 255, 255, 0.18 );
padding:16px;
}
input{
font-family:poppins;
width:450px;
transition:0.3s;
border-radius:5px;
border:none;
}
input:focus{
outline:none;
}
button{
color:white;
background-color:black;
border:none;
padding:8px;
border-radius:5px;
opacity:1;
font-family:poppins;
transition:0.3s;
}
button:hover{
opacity:0.7;
}
</style>
</head>
<body>
<div class="center">
<p><div class="container">
<h1>Copy Text to Clipboard using JavaScript</h1>
<input type="text" value="https://www.youtube.com/channel/UCLjS1fau8etNm-24r5kgxhQ" id="copyinput"readonly>
<button onclick="myFunction()">Copy text</button>
</div></p>
</div>
<script>
//js code for the copy to clipboard function
function myFunction() {
var copyText = document.getElementById("copyinput");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
</body>
</html>
And that's all for this project! Thanks for reading and do subscribe to our YouTube channel to support us in making web dev projects with free source code like this. Till, the next one,goodbye!
Post a Comment