diff --git a/src/js/utils/bounds.js b/src/js/utils/bounds.js index ec305427..e4722a85 100644 --- a/src/js/utils/bounds.js +++ b/src/js/utils/bounds.js @@ -3,7 +3,7 @@ import { extend, uniqueId } from './general'; import { isUndefined } from './type-check'; const zeroPosCache = {}; -let zeroElement = null; +const zeroElements = new Map(); export function getBounds(body, el) { let doc; @@ -143,10 +143,11 @@ export function getVisibleBounds(body, target) { } export function removeUtilElements(body) { - if (zeroElement) { - body.removeChild(zeroElement); + if (zeroElements.has(body)) { + body.removeChild(zeroElements.get(body)); } - zeroElement = null; + + zeroElements.delete(body); } /** @@ -187,7 +188,7 @@ function _getOrigin(body) { // jitter as the user scrolls that messes with our ability to detect if two positions // are equivilant or not. We place an element at the top left of the page that will // get the same jitter, so we can cancel the two out. - let node = zeroElement; + let node = zeroElements.get(body); if (!node || !body.contains(node)) { node = document.createElement('div'); node.setAttribute('data-tether-id', uniqueId()); @@ -199,7 +200,7 @@ function _getOrigin(body) { body.appendChild(node); - zeroElement = node; + zeroElements.set(body, node); } const id = node.getAttribute('data-tether-id'); diff --git a/test/unit/utils/bounds.spec.js b/test/unit/utils/bounds.spec.js new file mode 100644 index 00000000..24974753 --- /dev/null +++ b/test/unit/utils/bounds.spec.js @@ -0,0 +1,37 @@ +import { getBounds } from '../../../src/js/utils/bounds'; + +describe('Utils - bounds', () => { + describe('get bounds', () => { + let bodyElement; + + beforeEach(() => { + bodyElement = document.createElement('div'); + document.body.appendChild(bodyElement); + }); + + it('should get body offset', () => { + let bounds; + const element = document.createElement('div'); + element.style.position = 'absolute'; + element.style.top = '0'; + element.style.left = '0'; + bodyElement.appendChild(element); + bounds = getBounds(bodyElement, element); + + expect(bounds.top).toEqual(0); + expect(bounds.left).toEqual(0); + + bodyElement.style.position = 'absolute'; + bodyElement.style.top = '30px'; + bodyElement.style.left = '30px'; + bounds = getBounds(bodyElement, element); + expect(bounds.top, 'correct top bounds with body offset').toEqual(0); + expect(bounds.left, 'correct left bounds with body offset').toEqual(0); + }); + + afterEach(() => { + document.body.removeChild(bodyElement); + bodyElement = null; + }); + }); +});