Here are two JavaScripts. There is also a notification script.
I want to combine two javascripts in one and have both javascripts show the same notification.
This is the two different javascripts with the same notification.
<script>
function copy(that){
var text = that.textContent;
var input = document.getElementById('cb');
input.value = input.value + text +'n';
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
var notification = document.getElementById('symc');
notification.style.display = 'block';
setTimeout(() => {
notification.style.display = 'none';
}, 1000);
}
</script>
<script>
function co() {
var input = document.getElementById("cb");
navigator.clipboard.writeText(input.value);
var notification = document.getElementById('symc');
notification.style.display = 'block';
setTimeout(() => {
notification.style.display = 'none';
}, 1000);
}
</script>
<span id="symc">Copied</span>
<div id="ca">
<input id="cb">
<button onclick="co()">Copy</button>
</div>
This is the notification script
var notification = document.getElementById('symc');
notification.style.display = 'block';
setTimeout(() => {
notification.style.display = 'none';
}, 1000);
Please help me how can I mix two script in one js area…
<script>
</script>
Thanks.
Geovanny Okuneva is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Here is one function that can copy using the button or a click on a div content
I have used the clipboard API and delegation
SO does not allow access to the clipboard, so here is a jsfiddle that does allow it
https://jsfiddle.net/mplungjan/vxd5e7y3/
const input = document.getElementById("cb")
const button = document.getElementById("copy")
const container = document.getElementById("container")
const copyContent = (event) => {
const target = event.target
// If the copy button was clicked, copy from input field
if (target?.id === "copy") {
navigator.clipboard.writeText(input.value)
} else if (target.closest("div").matches(".copy-text")) {
const text = target.textContent
input.value = text
navigator.clipboard.writeText(text)
}
// Show the notification
const notification = document.getElementById("symc")
notification.hidden = false
setTimeout(() => (notification.hidden = true), 1000)
}
// Listen to the click event on the button to copy input field
button.addEventListener("click", copyContent)
// Add event listeners to other elements you want to copy from - her I use delegation
container.addEventListener("click", copyContent)
<span id="symc" hidden>Copied</span>
<div id="ca">
<input id="cb" />
<button id="copy">Copy</button>
</div>
<div id="container">
<div class="copy-text">Text 1</div>
<div class="copy-text">Text 2</div>
</div>
1