Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

612
Vistas
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

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda