Skip to content

Commit a970f0b

Browse files
committed
feat(domUtil): add getPositionInParent function
Find an element's offset, then add it to the offset of the parent until we are at the direct child of parentEl. Use-case: find scroll offset of any element within a scroll container
1 parent dc67300 commit a970f0b

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

js/utils/dom.js

+18
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,24 @@
1212

1313
ionic.DomUtil = {
1414

15+
/*
16+
* Find an element's offset, then add it to the offset of the parent
17+
* until we are at the direct child of parentEl
18+
* use-case: find scroll offset of any element within a scroll container
19+
*/
20+
getPositionInParent: function(el, parentEl) {
21+
var left = 0, top = 0;
22+
while (el && el !== parentEl) {
23+
left += el.offsetLeft;
24+
top += el.offsetTop;
25+
el = el.parentNode;
26+
}
27+
return {
28+
left: left,
29+
top: top
30+
};
31+
},
32+
1533
ready: function(cb) {
1634
if(document.readyState === "complete") {
1735
window.rAF(cb);

test/js/utils/dom.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
2+
describe('js/utils/dom', function() {
3+
4+
describe('getPositionInParent', function() {
5+
it('should return 0,0 if el===parentEl', function() {
6+
var el = {};
7+
expect(ionic.DomUtil.getPositionInParent(el, el)).toEqual({
8+
left: 0,
9+
top: 0
10+
});
11+
});
12+
it('should return 0,0 if el is null', function() {
13+
expect(ionic.DomUtil.getPositionInParent(null, null)).toEqual({
14+
left: 0,
15+
top: 0
16+
});
17+
});
18+
it('should return element offset{Top,Left} of el if el is parent\'s child', function() {
19+
var parent = {};
20+
var el = {parentNode: parent, offsetLeft: 3, offsetTop: 2};
21+
expect(ionic.DomUtil.getPositionInParent(el, parent)).toEqual({
22+
left: 3,
23+
top: 2
24+
});
25+
});
26+
it('should return added element offset{Top,Left} of all children up to parent', function() {
27+
var parent = {};
28+
var child1 = {parentNode: parent, offsetLeft: 5, offsetTop: 6};
29+
var child2 = {parentNode: child1, offsetLeft: 10, offsetTop: 11};
30+
expect(ionic.DomUtil.getPositionInParent(child1, parent)).toEqual({
31+
left: 5,
32+
top: 6
33+
});
34+
expect(ionic.DomUtil.getPositionInParent(child2, parent)).toEqual({
35+
left: 15,
36+
top: 17
37+
});
38+
});
39+
});
40+
});

0 commit comments

Comments
 (0)