clickoutsidehandler.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * @license Copyright (c) 2003-2019, 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 clicking **outside** of a specified set of elements, then fires an action.
  11. *
  12. * **Note**: Actually, the action is executed upon `mousedown`, not `click`. It prevents
  13. * certain issues when the user keeps holding the mouse button and the UI cannot react
  14. * properly.
  15. *
  16. * @param {Object} options Configuration options.
  17. * @param {module:utils/dom/emittermixin~Emitter} options.emitter The emitter to which this behavior
  18. * should be added.
  19. * @param {Function} options.activator Function returning a `Boolean`, to determine whether the handler is active.
  20. * @param {Array.<HTMLElement>} options.contextElements HTML elements that determine the scope of the
  21. * handler. Clicking any of them or their descendants will **not** fire the callback.
  22. * @param {Function} options.callback An action executed by the handler.
  23. */
  24. export default function clickOutsideHandler( { emitter, activator, callback, contextElements } ) {
  25. emitter.listenTo( document, 'mousedown', ( evt, { target } ) => {
  26. if ( !activator() ) {
  27. return;
  28. }
  29. for ( const contextElement of contextElements ) {
  30. if ( contextElement.contains( target ) ) {
  31. return;
  32. }
  33. }
  34. callback();
  35. } );
  36. }