UNPKG

1.84 kBJavaScriptView Raw
1(function (global, factory) {
2 if (typeof define === "function" && define.amd) {
3 define(["exports"], factory);
4 } else if (typeof exports !== "undefined") {
5 factory(exports);
6 } else {
7 var mod = {
8 exports: {}
9 };
10 factory(mod.exports);
11 global.eventMatches = mod.exports;
12 }
13})(this, function (_exports) {
14 "use strict";
15
16 Object.defineProperty(_exports, "__esModule", {
17 value: true
18 });
19 _exports.default = eventMatches;
20 /**
21 * Copyright IBM Corp. 2016, 2018
22 *
23 * This source code is licensed under the Apache-2.0 license found in the
24 * LICENSE file in the root directory of this source tree.
25 */
26
27 /**
28 * @param {Event} event The event.
29 * @param {string} selector The selector.
30 * @returns {Element}
31 * The closest ancestor of the event target (or the event target itself) which matches the selectors given in parameter.
32 */
33
34 function eventMatches(event, selector) {
35 // <svg> in IE does not have `Element#msMatchesSelector()` (that should be copied to `Element#matches()` by a polyfill).
36 // Also a weird behavior is seen in IE where DOM tree seems broken when `event.target` is on <svg>.
37 // Therefore this function simply returns `undefined` when `event.target` is on <svg>.
38 var target = event.target,
39 currentTarget = event.currentTarget;
40
41 if (typeof target.matches === 'function') {
42 if (target.matches(selector)) {
43 // If event target itself matches the given selector, return it
44 return target;
45 }
46
47 if (target.matches("".concat(selector, " *"))) {
48 var closest = target.closest(selector);
49
50 if ((currentTarget.nodeType === Node.DOCUMENT_NODE ? currentTarget.documentElement : currentTarget).contains(closest)) {
51 return closest;
52 }
53 }
54 }
55
56 return undefined;
57 }
58});
\No newline at end of file