I’m a beginner and could use some help. I used this W3 Schools script to copy a discount code on my Shopify site.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard2
I have it set up pretty well, but ran into an issue. When you click copy the input field border gets bold or wider and the text turns white and highlighted in blue. For some reason on my site it adds a second gray border surrounding the input field/border, and the text stays black with a gray highlight.
No matter what I try with CSS in styles or in the script at the bottom. I can’t make any changes to this after-click border and highlight without messing up something else.
I don’t see anything in the code controlling this.
Any ideas?
Again, no matter what I try with CSS in styles or in the script at the bottom. I can’t make any changes to this after-click border and highlight without messing up something else.
>Solution :
A solution to this problem is to deselect it with the JS code. You can use this: window.getSelection().removeAllRanges();. to unselect the input box, just use your-input-id.blur();
FULL EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body>
<p>Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.</p>
<input type="text" value="Hello World" id="myInput">
<div class="tooltip">
<button onclick="myFunction()" onmouseout="outFunc()">
<span class="tooltiptext" id="myTooltip">Copy to clipboard</span>
Copy text
</button>
</div>
<script>
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
window.getSelection().removeAllRanges();
const myInput = document.querySelector('input'); // Replace with your input selector
myInput.blur(); // Unselect the input field
var tooltip = document.getElementById("myTooltip");
tooltip.innerHTML = "Copied: " + copyText.value;
}
function outFunc() {
var tooltip = document.getElementById("myTooltip");
tooltip.innerHTML = "Copy to clipboard";
}
</script>
</body>
</html>