I'm trying to copy text using clipboard.js but it's not copying. here's my code
$(document).ready(async function () {
var html = ''
var script = '<script>'
let response = await ajax('/admin/all_files', 'POST', '')
for (let i = 0; i < response.length; i++) {
var url = window.location.origin + '/get_file/' + response[i][0]
html += `<div>
<img src="`+ url +`" alt="">
<div>
<button id="ttc_`+ i +`_url" data-clipboard-text=`+ url +`>URL</button>
</div>
</div>`
script += `var ttc_`+ i +`_url = new Clipboard('#ttc_`+ i +`_url');`
}
$('#insert_image_modal_body').html(html)
script += '</script>'
$('body').append(script)
})
my ajax function is:
async function ajax(url, method, data) {
return $.ajax({
url: window.location.origin + url,
method: method,
data: data
}).done((response) => {
return response
});
}
it shows nothing, no error but the text is not copying too.
Couple of things, I noticed in some areas you were using
varwhen you could've been usingletorconst(as of ES6). Here's a good article that will describe the differences for you: https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/Secondly, your code seems to generate javascript, within javascript... it's possible what you're doing, but might as well just do what you're doing within the existing script tags that you already have.
Thirdly, you are attempting to use template literals to form you strings. That's great, however you aren't leveraging the most important part, and that's the ability to inject values directly into the string using the
${}notation.Regarding the clipboard code. Since you are utilizing
data-clipboard-textthere's no need to require each button to have a unique id. Instead you can add a class, for examplecopy-btnthat you add to each button. This way you only have to callnew ClipboardJS('.copy-btn');once!Taking all of these into consideration, I've cleaned up your code a bit below: