Search code examples
javascriptjqueryhandlebars.js

How to toggle hide/show inside the handlebars template?


I'm very new to programming in general, so I think that my question will be very easy to answer. Sorry if some of the terminologies is a bit off, please correct me.

How do I write a template that hides-shows different parts of one element in an array?

I have an array with headers and text. I need to be able to show/hide the text when the corresponding header is clicked. Here is what I have in the HTML:

<script id="maino" type="text/x-handlebars-template">
    <div class="row">
      {{#each names}}
          <div class="col-xs-12 col-md-3"> 
            <div data-id="{{@index}}">
                 <h4 id="button" > {{name}} </h4>
                 <p id="ff" >{{text}}</p>
            </div>
          </div> 
      {{/each}}
    </div>
</script>

This is what's in the js file:

$("#button").click(function(){
    console.log(this);
    var a = "#ff";
    $(a).toggle();
});

It applies toggle only to the [0] element. How can I change this? Is there any other attribute that I could bind to the @index and use in the click function?

Thank you in advance!

P.S. The array:

var banners = {
names: [
    {
        name: "Lorem ipsum",
        text: "dolor sit amet, consectetur "
    },
    {           
        name: "aboris nisi",
        text: "Duis aute irure dolor in reprehenderit "
    },
    {
        name: "culpa officia",
        text: "ccaecat cupidatat non"
    }
  ]
}

Solution

  • You are repeating the ff id. Tag element ids should be unique. On the each loop you are creating 3 <p> tags with the same id. Try concatenating the index value to the id, something like ff-{@index} and use that to do the toggle.