I came across this weird behavior. I want to add a html template containing an onclick behavior. So I tried the code below. The problem is that the function callFunction
inside is executed automatically. My guess is that callFunction
is executed when parsing the interpolation string in innerHTML. Is there a way around this behavior ? Thanks you
const container = document.getElementById("test1"); function callFunction() { console.log('called'); } container.innerHTML = `<button onClick="${callFunction()}"> Click on me</button>`
<div id="test1"></div>
Advertisement
Answer
Expressions inside template literals are executed immediately. If you are creating an HTML string, you don’t need to call the function in the same scope as it is created. You don’t even need template literals. You just need to create a string with an onClick
attribute.
container.innerHTML = '<button onClick="callFunction()"> Click on me</button>'
const container = document.getElementById("test1"); function callFunction() { console.log('called'); } container.innerHTML = `<button onClick="callFunction()"> Click on me</button>`
<div id="test1"></div>