Sometimes you may find yourself wanting to detect clicks outside of your custom element in Polymer, the most popular use cases are when: closing a menu or closing a dropdown when the user clicks outside of it.
Below is a quick and easy way to achieve this:
- Add an event listener to the document (*If your component opens a menu or dropdown when clicked then I would suggest only adding the event listener when that element is ‘opened’ for efficiency.)
- Add the listener function that checks if the click event is inside or outside of the component. You can use Polymer.dom(event).path to get the path/array of nodes through which the event passes through and check if any of the nodes match the current component.
openMenu() { //code to open menu here document.addEventListener('tap', this._checkOutsideClick.bind(this)); } closeMenu() { //code to close menu here document.removeEventListener('tap', this._checkOutsideClick.bind(this)); } /** * This function is triggered on any click. * @param {Object} e - the event */ _checkOutsideClick(e) { // get the array of nodes through which the event passes through // if any of the nodes match the component element then we know // the click was inside of the element, so do nothing. if none match, // then we know the click was outside of the element so close the menu const path = Polymer.dom(e).path; let insideMenuClick = false; if(!_.isEmpty(path)) { insideMenuClick = !_.isEmpty(path.find((el) => { return el == this; })); } if(insideMenuClick) { //inside element } else { //outside element this.closeMenu(); } }
Leave a Reply