Reputation: 778
I am dynamically inserting html in to the DOM when a form is submitted. When this content is created, I would like to add a delete function when the corresponding button is created. The issue I am facing is that I am unsure how I can use a function in a template literal that has a parameter. My function keeps running when the page loads!
const deletePost = (id) => {
console.log("Delete Button Was clicked ");
}
function renderPost(title, date, body, author, id) {
// renderPost()
postHolder.innerHTML += `
<div class="post">
<div class="deleteButton">
<button onclick=${deletePost(id)}>
<i class="fas fa-trash"></i>
</button>
</div>
<div class="headerPosted">
<div class="titlePosted">
${title}
</div>
<div class="datePosted">
${date}
</div>
</div>
<div class="bodyPosted">
${body}
</div>
<div class="authorPosted">
-"${author}"
</div>
</div>`;
}
Here is a codepen to test: Codepen
Upvotes: 0
Views: 154
Reputation: 68943
Simply wrap the dynamic variable with ${...}
.
Try
<button onclick=deletePost(${id})>
Demo:
const deletePost = (id) => {
console.log("Delete Button was clicked.");
}
document.addEventListener('DOMContentLoaded', (event) => {
function renderPost(title, date, body, author, id) {
const postHolder = document.getElementById('postHolder');
postHolder.innerHTML += `
<div class="post">
<div class="deleteButton"><button onclick=deletePost(${id})><i class="fas fa-trash"></i></button></div>
<div class="headerPosted">
<div class="titlePosted">
${title}
</div>
<div class="datePosted">
${date}
</div>
</div>
<div class="bodyPosted">
${body}
</div>
<div class="authorPosted">
-"${author}"
</div>
</div>`;
}
renderPost('test', new Date(), 'some body', 'test author', 123);
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div id="postHolder"></div>
Upvotes: 3