Kahn
Kahn

Reputation: 449

Polymer 3, onfocusout or onblur events

how can I invoke onfocusout or onblur menthods in Polymer 3? on-click event works perfectly when I click on menu button but the on-blur or on-focusout doesn't work? I want the menu to close when someone click outside menu?

static get properties() {
    return {
      _openMenu: Boolean
    };
  }

_toggleMenu(){
  this._openMenu= !this._openMenu;
}

_closeMenu(){
   this._openMenu= false;
}

My button looks something like this

<button on-click="${this._toggleMenu()}" on-blur="${this._closeMenu()}">

Upvotes: 1

Views: 562

Answers (2)

Kahn
Kahn

Reputation: 449

Ok I fixed my problem like this. Just removed the on-click and on-blur event from my button

<button>Click</button>

On connectedCallBack() I add eventListener to window object, so I can find out where the click has happened. If the click is inside the menu then I toggle my _openMenu, if the click is outside Menu then I false _openMenu

connectedCallback() {
    super.connectedCallback();
    this._boundClickHandler = this._clickHandler.bind(this);
    window.addEventListener('click', this._boundClickHandler);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    window.removeEventListener('click', this._boundClickHandler);
  }

  _clickHandler(event) {
    let clickedInsideMenu = false;
    event.path.forEach((node) => {
      if (!clickedInsideMenu && node === this) {
        clickedInsideMenu = true;
      }
    });

    if (clickedInsideMenu) {
      this._toggleMenu();
    } else {
      this._openMenu= false;
    }
  }

Upvotes: 2

Binh Bui
Binh Bui

Reputation: 343

That's because on-blur and on-focusout are not defined yet in Polymer library. You can check the existing support gesture events here.

What you can do is to add events imperatively by selecting the menu then add an event to it.

Upvotes: 1

Related Questions