Template strings are a way to generate strings. Anything passed into ${...}
will be converted to a string.
If you want to a call a function from an onclick
attribute then the value of that attribute needs to be a string of JS that calls the function:
onclick="me()"
… not the function itself.
Of course, this requires that the me
variable holding the function be a global so that it is in scope for the onclick
attribute.
Intrinsic event attributes have a bunch of issues surrounding the need for globals and weird things they do with scope and are best avoided.
I recommended using addEventListener
instead.
The best way to use it depends on the wider context.
Possibly you should use document.querySelector
to find the element in the DOM after creating a DOM from the string and then call addEventListener
on the result.
Possibly you should call addEventListener
on the window
in advance and have a delegated event handler.
Possibly you need to have some element-specific context made available to that function which you could provide by using data-*
attributes.
function me(event) {
const el = event.target;
if (el.tagName.toLowerCase() !== "button") return;
alert("Hello " + el.dataset.name);
}
window.addEventListener("click", me);
function addElement(message) {
const html = `<button type="button" data-name="${message}">${message}</button>`;
document.querySelector("#container").insertAdjacentHTML('beforeend', html);
}
addElement("Alice");
addElement("Bob");
<div id="container"></div>