Passing onclick event in template literal

Viewed 7686

I'm trying to pass url through onclick event, its not working. there is <body onload="displayBookmarks()"> to initialise displayBookmarks function as soon as the page gets loaded

function deleteBookmark(url){
    alert(url);
};

function displayBookmarks(){
    bookmarksResults.innerHTML = "";
    for (let a in bookmarks){
        let name = bookmarks[a].name;
        let url =  bookmarks[a].url;
        bookmarksResults.innerHTML += `<div class="well"> <h3> ${name} <a class="btn btn-default" target="_blank" href=${url} >Visit</a>  <a onclick=${deleteBookmark(url)} class="btn btn-danger" >Delete</a></h3></div>`
    }
}

The main problem is onclick=${deleteBookmark(url)} As soon as the page loads it starts displaying the url but I want to to be shown only when delete button is pressed.

2 Answers

I've found that there is another way to do this with encapsulation. I don't know if I would recommend doing it like this at all but since you've asked the question.

const app = document.getElementById("app");

const button = ((app) => {
  
  let _url;
  
 const _log = (data) => {
   console.log(data);
  }
  
  let _content = `<button onclick="(${_log})('${_url}')">test</button>`;
  
  const _setContent = () => {
   _content = `<button onclick="(${_log})('${_url}')">test</button>`;
  }
  
  const _setUrl = (url) => {
   _url = url;
  }
  
  return {
   setUrl: (url) => {
     _setUrl(url);
      _setContent();
    },
   render: () => {
     app.innerHTML = _content;
    }
  }
})(app)

const url =  'www.something.com';
button.setUrl(url);
button.render();
<section id="app">...</section>

Related