I need to copy the email address when someone clicks on the associated image.
I had it all written in a html file, but now I'm transferring my code in a .js
so I can use JSON
to store the staff data instead of writing them one by one. The problem is that I had a function that was called when the image is clicked that doesn't work when I use buildStaff
.
I had it written like this:
<img class="imageCopy" id="copy-button-${ID}" src="copyIcon.png" onclick="copyEmail('email-1', 'toolTip-1')">
And I have this now :
function buildStaff(staff, ID) {
return `
<div class="staffGroup">
<span class="staffTextGroup">
<p class="name"> ${staff.name} <\p>
<span class="email" id="email-${ID}"> ${staff.email} <\span>
</span>
<span class="copyButton">
<span class="tootTipText" id="tootTip-${ID}"> Copied. <\span>
<img class="imageCopy" id="copy-button-${ID}" src="copyIcon.png">
<\span>
</div>
`;
}
I just can't find a way to use the dynamic variables for the copyEmail
function.
Thank you very much! This is my first time doing a website, so I'm a bit lost.
EDIT
This is the complete original JS
code, but without the onclick="copyEmail()
in the img
.
$(document).ready(() => {
let staffAnchor = $('[staff-anchor]');
fetchFromJson(STAFF_JSON_FILE_PATH, StaffData => {
StaffData.staff.forEach((staff, i) => {
const ID = `staff-${i}`;
let staffElement = buildStaff(staff, ID);
$(staffAnchor).append(staffElement);
});
});
});
function fetchFromJson(jsonFilePath, callback) {
$.getJSON(jsonFilePath, callback);
}
function buildStaff(staff, ID) {
return `
<div class="staffGroup">
<span class="staffTextGroup">
<p class="name"> ${staff.name} <\p>
<span class="email" id="email-${ID}"> ${staff.email} <\span>
</span>
<span class="copyButton">
<span class="tootTipText" id="tootTip-${ID}"> Copied. <\span>
<img class="imageCopy" id="copy-button-${ID}" src="copyIcon.png" alt="copy image">
<\span>
</div>
`;
}
function copyEmail(id, tooltip) {
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
The problem is that I can't find a way to use copyEmail()
now that I can't simply write it in the HTML
.