Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

614
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda