clickoutsidehandler.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module ui/bindings/clickoutsidehandler
  7. */
  8. /* global document */
  9. /**
  10. * Handles a DOM `click` event outside of specified elements and fires an action.
  11. *
  12. * Note that it is not handled by a `click` event, this is to avoid situation when click on some trigger
  13. * opens and closes element at the same time.
  14. *
  15. * @param {Object} options Configuration options.
  16. * @param {module:utils/dom/emittermixin~Emitter} options.emitter The emitter to which this behavior should be added.
  17. * @param {Function} options.activator Function returning a `Boolean`, to determine whether handler is active.
  18. * @param {Array.<HTMLElement>} options.contextElements `HTMLElement`s that clicking inside of any of them will not fire the callback.
  19. * @param {Function} options.callback Function fired after clicking outside of specified elements.
  20. */
  21. export default function clickOutsideHandler( { emitter, activator, callback, contextElements } ) {
  22. emitter.listenTo( document, 'mouseup', ( evt, { target } ) => {
  23. if ( !activator() ) {
  24. return;
  25. }
  26. for ( const contextElement of contextElements ) {
  27. if ( contextElement.contains( target ) ) {
  28. return;
  29. }
  30. }
  31. callback();
  32. } );
  33. }