1

I have this template string

const tdValue = `<td><a onclick=${me}>Show</a></td>`

and I have a function like this in the same file

function me() {
  alert('me');
}

I need to invoke the function when click, but I cannot invoke this function the way I defined, If I try

<td><a onclick=${me()}>Show</a></td>

then function get invoked immediately after the render, which is not I expected

Any solution for this?

SFernando
  • 1,074
  • 10
  • 35

4 Answers4

3

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>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for the detailed explanation Quentin, I think its better to add an event listener for that as it is not giving me errors like 'function not defined' – SFernando Nov 19 '20 at 14:30
0

You need to specify the what happens when clicked. In this case, call the function.

const tdValue = `<td><a onclick="me()">Show</a></td>`

function me() {
  alert('me');
}
ChrisG
  • 2,637
  • 18
  • 20
-1

Remove parenthesis:

<td><a onclick=${me}>Show</a></td>
Aadil Mehraj
  • 2,586
  • 1
  • 7
  • 17
-2

You must first add jquery to your project

<html>
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"``
  crossorigin="anonymous"></script>
 </body>
</html>```