Search code examples
polymerweb-component

Create toggle menu using Polymer


I'm trying to create a toggle menu with Polymer. What I want is plain simple, when I click an item I want to display only the related div as the content. I'm using the core-scalffold element which gives you a menu and a content layout.

Which should be the best approach to accomplish this using polymer components and events?

 <core-scaffold>
  <core-header-panel navigation flex>
    <core-toolbar id="navheader">
    </core-toolbar>
    <core-menu>
      <core-item label="Content 1"></core-item>
      <core-item label="Content 2"></core-item>
    </core-menu>
  </core-header-panel>

  <span tool>Title</span>

  <div class="content1">
      Hi there content1!
  </div>
   <div class="content2">
      Hi there content2!
  </div>
</core-scaffold>

Solution

  • The core-pages element provides a way of making selectable sections, so this is a good choice for the content divs. Then, since core-menu and the core-pages both have selected properties, it's easy to bind the two elements together. To use Polymer data-binding, we have to use a template. If we put the whole thing in an auto-binding template we get something like this:

    <template is="auto-binding">
    
      <core-scaffold>
    
        <core-header-panel navigation flex>
          <core-toolbar id="navheader">
          </core-toolbar>
          <core-menu selected="0" selectedIndex="{{selected}}">
            <core-item label="Content 1"></core-item>
            <core-item label="Content 2"></core-item>
          </core-menu>
        </core-header-panel>
    
        <span tool>Title {{selected}}</span>
    
        <core-pages selected="{{selected}}">
          <div class="content1">
              Hi there content1!
          </div>
          <div class="content2">
              Hi there content2!
          </div>
        </core-pages>
    
      </core-scaffold>
    
    </template>
    

    Note: I bound selectedIndex property of core-menu so I could use selected for setting the default.

    http://jsbin.com/wivec/1/edit

    If you really want a solution that uses events instead of binding, let me know.