Search code examples
polymerpolymer-1.0

Polymer - can not click event outside of element to close itself


Polymer 1.*

I had to write my own dropdown menu. I need to close the menu when the user clicks outside of the element. However, I am not able to catch the event when a user clicks outside of the element so I can close the menu.

Any ideas what I am doing wrong?

EDIT: I've studying paper-menu-button which closes paper-listbox when I click outside the element.... but I don't see anywhere where it catches that event https://github.com/PolymerElements/paper-menu-button/blob/master/paper-menu-button.js#L311

<dom-module id="sp-referrals-reservations-dropdown">
  <template>
    <style include="grid-dropdown-styles">


    </style>

    <div id="dropdown" class="grid-dropdown">
        <paper-listbox>

          <div class="grid-dropdown-item">Convert to stay</div>
          <div class="grid-dropdown-item">Cancel reservation</div>
          <div class="grid-dropdown-item">Delete reservation</div>

        </paper-listbox>
    </div>


  </template>

  <script>
    (function() {
      'use strict';
      Polymer({
        is: 'sp-referrals-reservations-dropdown',

        behaviors: [Polymer.IronControlState],

        properties: {
        },

        listeners: {
          'tap': '_close',
          'click': '_close',
          'blur': '_close',
          'focusout': '_close',
          'focusChanged': '_close',
          'focus-changed': '_close',
          'active-changed': '_close',
          'activeChanged': '_close',
          'iron-activate': '_close',
          'ironActivate': '_close',
        },

        open: function(e) {

        },

        _close: function() {
          console.log('aaa');
          this.$.dropdown.style.display = "none";
        },

      });
    })();
  </script>
</dom-module>

Solution

  • I am not sure, will it be enough, but if you wrap the sp-referrals-reservations-dropdown element with a parent-element then you can listen to parent-element events same as its child.

     <parent-element></parent-element>
    
      <dom-module id="parent-element">
        <template>
          <style>
            :host {
              display:block;
              background:green;
              width:100%;
              height:100vh; }
          </style>
    
          <sp-referrals-reservations-dropdown id="spref"></sp-referrals-reservations-dropdown>
    

    At parent's script:

    Polymer({is:'parent-element', properties:{}, 
               listeners:{ 'tap': '_taped'},
    
               _taped:function(t){
                 this.$.spref._close();
               }
              });
    

    this _taped functions will call child's _close function. Hope its help.

    • Incase of needed more. We can develop this.

    Demo

    EDIT

    Wrap your element into paper-dialog. And at ready:function() call

    this.$.dialog.open()

    Then when you click outside of the element. paper-dialog will close automatically.