Reputation: 163
I am a complete beginner in HTML and CSS, and new to this community, this is my first post, I have checked a lot of similar posts, but unfortunately wasn't able to find exactly what I am looking for. I really hope someone can help me as I have not been able to find a solution on my own.
What I'm trying to accomplish:
I have managed to do it on my own, but I think it's not the most convenient way, but as a complete beginner I wasn't able to find a better solution, if someone with experience can take a look and suggest other options I would really appreciate it.
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
}
<div class="columnen">
<p>1. Line one.<br>
2. Line two.<br>
3. Line three.<br>
</p>
<button onclick="myFunction()">Copy text</button>
</div>
<div class="textniz">
<textarea id="myInput" name="myInput">1. Line one.
2. Line two.
3. Line three.
</textarea>
</div>
The solution works, but the problem I have is that I have to edit each text two times, as I use the first part of the code visible for users and second part of the code invisible for users, but which actually makes the job done.
Maybe I can just style the class "textniz" or textarea, but I don't know how to stop it from highlighting the text.
Hopefully I have made sense with my request and someone from the website can take a look. Cheers.
Upvotes: 1
Views: 1923
Reputation: 846
To stop the textarea from being highlighted, we can create an another textarea and put it away from the page and put the original textarea's value in our new textarea and select its value which will not be visible to the user, and the text will be copied. After copying, we can remove the newly created textarea.
function myFunction() {
var value = document.getElementById("myInput").value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText)
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
console.log(value)
copyText.remove()
}
1. Line one.
2. Line two.
3. Line three.
<div class="columnen">
<p>1. Line one.<br>
2. Line two.<br>
3. Line three.<br>
</p>
<button onclick="myFunction()">Copy text</button>
</div>
<div class="textniz">
<textarea id="myInput" name="myInput">1. Line one.
2. Line two.
3. Line three.
</textarea>
</div>
Upvotes: 2