3

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.

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
sskumar
  • 31
  • 1
  • 5
  • 2
    Simple: Don't use html strings and [inline event handlers](https://stackoverflow.com/q/6941483/1048572). Template literals are not your real problem. – Bergi Jul 16 '17 at 14:03
  • Why are you using an interpolation for the value of the event handler attribute? You indeed don't want to call the function when constructing the string. You want a literal `onclick="deleteBookmark(url)"` to appear in the HTML. – Bergi Jul 16 '17 at 14:05
  • `... ${deleteBookmark(url)} ... ` is immediately evaluated when the template literal is defined. Since `deleteBookmark(url)` is a function invocation expression, this is the cause of your problem. The `${...}` inside backticks _evaluates_ Javascript code. – try-catch-finally Jul 16 '17 at 15:28

2 Answers2

4

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>
3

const markUp = `
    <button onclick="myFunction()">Click me</button>
`;

document.body.innerHTML = markUp;

window.myFunction = () => {
    console.log('Button clicked');
};
Miroslav Savovski
  • 2,300
  • 2
  • 10
  • 12