Reputation: 342
I want to create a DOM element from an HTML string. Inside that string, I have a button that should call a global function called downloadFile
with predefined arguments.
My first try:
<button onclick="downloadFile(${message_result})">Download</button>
But this failed to work.
Whole code looks like this
function downloadFile(result){
console.log(result)
}
(() => {
const msg = {user: 'User', message: 'Message', result: {}} // any
var markup = `
<h4>${msg.user}</h4>
<p>${msg.message}</p>
<button onclick="downloadFile(message_result)">Download</button>
`
document.body.innerHTML = markup
})()
the error: Uncaught ReferenceError: message_result is not defined at HTMLButtonElement.onclick
any suggestions how i can pass a variable into my function
Upvotes: 0
Views: 442
Reputation: 5462
Let's first solve your problem then talk about a better approach.
If we assume msg.result
is a string: You need to wrap it with quote marks.
<button onclick="downloadFile('${message_result}')">Download</button>`;
But if your msg.result
is not a simple string or you want to take the right path to the solution, then we need to move next approach.
// This is your downloadFile function
const downloadFile = (data) => {
console.log(data)
}
// This function creates download buttons
const createDownloadButton = (response) => {
const markup = `
<h4>${response.user}</h4>
<p>${response.message}</p>
<button>Download</button>
`
const container = document.createElement("div")
container.innerHTML = markup;
// Here, we assign "click" functionality dynamically even before we inject the element into DOM
container.getElementsByTagName("button")[0].addEventListener('click', () => {
downloadFile(response.result)
})
document.body.append(container)
}
// Fetch your response from an external service
const msg = {
user: 'Username',
message: 'Message',
result: {
file: {
link: 'https://stackoverflow.com'
}
}
}
// Call function to create download button
createDownloadButton(msg)
Upvotes: 1
Reputation: 1389
If message_result
is a variable, like msg.message
, then you need to reference it similarly.
var markup=`
<h4>${msg.user}</h4>
<p>${msg.message}</p>
<button onclick="downloadFile('${message_result}')">Download</button>`;
Upvotes: 0