Search code examples
javascripthandlebars.js

How to call javascript function from handlebars js template?


On button click, I have to change the CSS width :

 {{#if this.text}} 
     <div id = {{this.id}} class="sidepanel">
        <button  class="closebtn" onclick="{{close(this)}}">×</button>
        <h1> {{this.text}}</h1>
     </div> 
   <button  onclick="{{open(this)}}" class="openbtn">Open</button> 
 {{/if}}

inside script file I have two functions:

  function close(data) {
     document.getElementById(data.id).style.width = "0px"
   }

  function open(data) {
    document.getElementById(data.id).style.width = "100%"
  }

Problem: I am not sure how to call these functions from the handlebar template


Solution

  • open and close are not available to the Handlebars context, so we definitely don't want to be invoking them from within handlebars expressions {{ }}.

    The part about these invocations that is known to Handlebars is the id, so the simplest thing to do would be to render the id so that it will be passed to the function when the button it is attached to is clicked.

    Note: I am going to rename these functions from open and close to openSidepanel and closeSidepanel because open is an existing function on the window.

    Our function definitions becomes:

    function closeSidepanel(id) {
      document.getElementById(id).style.width = "0px"
    }
    
    function openSidepanel(id) {
      document.getElementById(id).style.width = "100%"
    }
    

    and our template becomes:

    <div id = {{this.id}} class="sidepanel">
      <button  class="closebtn" onclick="closeSidepanel('{{this.id}}')">×</button>
      <h1> {{this.text}}</h1>
    </div> 
    <button  onclick="openSidepanel('{{this.id}}')" class="openbtn">Open</button> 
    

    Notice that we wrap quotes around what is rendered for our id so that it will be treated as a JavaScript string.

    I have created a fiddle for your reference.