4

I'm using Mustache.js for a project, but I'm stuck trying to include a jQuery button inside a template.

I made a template to display the five candidates for my state's governor election. In a JSON, I included their name, photo and party affiliation. I load the data into this template:

{{ #governor }}
    <div class="cand-{{ head }}">
        <div class="head">
            <img src="{{ picture }}">
        </div>
        <div class="bio">
            <h5>{{ name }}</h5>
                <i class='fa fa-circle' style='color: {{ color }}'></i> {{ party }}<br>  
        </div>
    </div>
{{ /governor }}

Now, I want to include a jQuery button underneath the party line that will hide the other candidates and bring up a div with details that will close with another button nested within. However, the button doesn't work inside the Mustache template. It works fine outside. Here's my button code:

<button class="open-govA">Details</button>

<script>
$( ".open-govA" ).click(function() {
  $( ".details-govA" ).show( "slow" );
  $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").hide( "slow" );
  });

$( ".close-govA" ).click(function() {
  $( ".details-gov" ).hide( "slow" );
   $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").show( "slow" );
  });
</script>

How should I proceed?

  • use event delegation for dynamically created elements. This issue gets asked numerous times a day ... should be easy web search – charlietfl Oct 12 '14 at 22:22
  • Doesn't seem to work. Keep in mind the template is within –  Oct 12 '14 at 23:45
  • yes it definitely does and you need to use `on()` and delegate those events. google `jquery event delegation` – charlietfl Oct 12 '14 at 23:49
  • Still struggling. I've researched jQuery event delegation and couldn't find anything about putting a button in a script template. I tried on(), but it only works with a button outside the template. –  Oct 13 '14 at 02:39
  • must not be using `on()` correctly. – charlietfl Oct 13 '14 at 12:50

1 Answers1

3

As everybody already said, you should use event delegation with the jQuery on function:

<script>
  $( "#parentInPage" ).on("click", ".open-govA", function() {
    $( ".details-govA" ).show( "slow" );
    $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").hide( "slow" );
  });

  $( "#parentInPage" ).on("click", ".close-govA", function() {
    $( ".details-gov" ).hide( "slow" );
    $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").show( "slow" );
  });
</script>

In case you don't have a common element on the page where you append all those templates, you can use "body". Just be careful with an eccessive use of that - see the Event Performance section on the jQuery ono documentation.

Community
  • 1
  • 1
MarcoL
  • 9,829
  • 3
  • 37
  • 50
  • Thanks for the example. I found out I wasn't using the right #parentInPage value. –  Oct 14 '14 at 15:51