jQuery get position of element relative to another element
So I have a div like:
<div class="uiGrid">
<div class="trigger"></div>
</div>
And I want to know the position of trigger to uiGrid and have tried both these:
$('.trigger').offset('.uiGrid');
$('.trigger').position('.uiGrid');
but neither get it. Offset is relative to the document and position is relative to the parent and not the specified element.
How would I do this? Thanks
just do the subtraction your self...
var relativeY = $("elementA").offset().top - $("elementB").offset().top;
what you can do here is basically, subtract parent property value from child property value.
var x = $('child-div').offset().top - $('parent-div').offset().top;
You're missing the point here....
Besides that, try:
myPosY = $('.trigger').offset().left - $('.uiGrid').offset().left;
myPosX = $('.trigger').offset().top - $('.uiGrid').offset().top;
The problem for me was the fact that I was in a div with a scrollbar and that I had to be able to take into account the hidden part down to the root element.
If I use ".offset()" it gave me wrong values, because it does not take into consideration the hide part of scrollbar as it is relative to the document.
However, I realized that the ".offsetTop" property relative to its first parent positioned (offsetParent) was always correct. So I made a loop to go recursively to the root element by additionning the values of ".offsetTop":
I did my own jquery function for that:
jQuery.fn.getOffsetTopFromRootParent = function () {
let elem = this[0];
let offset = 0;
while (elem.offsetParent != null) {
offset += elem.offsetTop;
elem = $(elem.offsetParent)[0];
if (elem.offsetParent === null) {
offset += elem.offsetTop;
}
}
return offset;
};
You can use the same with ".offsetLeft" I suppose...
If you want to get position of element relative to another element to answer the question:
let fromElem = $("#fromElemID")[0];
let offset = 0;
while (fromElem.id.toUpperCase() != "toElemID".toUpperCase()) {
offset += fromElem.offsetTop;
fromElem = $(fromElem.offsetParent)[0];
}
return offset;
An element (offsetParent) is said to be positioned if it has a CSS position attribute of relative, absolute, or fixed.
ReferenceURL : https://stackoverflow.com/questions/8342667/jquery-get-position-of-element-relative-to-another-element
'code' 카테고리의 다른 글
테스트 리소스 파일을 얻는 방법은 무엇입니까? (0) | 2020.12.24 |
---|---|
애플리케이션 버전에 따라 Inno Setup 설치 프로그램의 버전을 자동으로 설정하려면 어떻게해야합니까? (0) | 2020.12.24 |
Git 푸시 오류 : "origin이 git 저장소로 보이지 않습니다." (0) | 2020.12.24 |
노드 스트림에서 종료 및 종료 이벤트의 차이점은 무엇입니까? (0) | 2020.12.24 |
react.js의 ng-if에 해당하는 것은 무엇입니까? (0) | 2020.12.24 |