Getting every offsetParent or the total offSetTop and total offSetLeft - javascript

I want to get the total offSetTop and the total offSetLeft of a child element which have many level of parent element and may be adding up.
Is that any shorthand way, besides of adding one by one in manual ways?

To provide an answer without jQuery:
var a = Element, b = 0, c = 0;
while (a) {
b += a.offsetLeft;
c += a.offsetTop;
a = a.offsetParent;
}
Where Element is your Element node for which you need an offsetLeft and offsetTop.

using jQuery: $( node ).offset() then .top and .left

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position.
let { left, top } = domNode.getBoundingClientRect();
left += window.scrollX;
top += window.scrollY;

Related

Calculate offset top of elements inside of a scrollable div

How can I calculate offset top inside a scrollable div? I have two divs that I want scroll inside my content div, and I want to set 2 variables to true/false, depending on where they are positioned inside that content div.
I tried something like this but I guess it calculates the entire page offset, it doesn't really work. I bind scroll to that content div, and I want to calculate their positon:
angular.element(slideContent).bind("scroll", function () {
var contentScrollTop = angular.element(slideContent).scrollTop();
var slideOneOffset = slideOne.offset().top;
var slideTwoOffset = slideTwo.offset().top;
var firstSlideDistance = (contentScrollTop - slideOneOffset);
var secondSlideDistance = (contentScrollTop - slideTwoOffset);
});
I think this should get you most of the way there:
// Position of first element relative to container top
var scrollTop = $(".container .element").offset().top - $(".container").offset().top;
// Position of selected element relative to container top
var targetTop = $(".container > *").offset().top - $(".container").offset().top;
// The offset of a scrollable container
var scrollOffset = scrollTop - targetTop;
// Scroll untill target element is at the top of its container
$(".container").scrollTop(scrollOffset);
———————————
EDIT (May 31 2018)
I guess this is better:
var scrollOffset = $(".container .element")[0].offsetTop - $(".container")[0].offsetTop

How to get the left and top position of a child element of its parent

I have a parent-child structure of div elements (parent is the div called dartboard, a child div called rotatingDiv and that then has a child called crosshair).
dartboard
> roatingDiv
> crosshair
The dartboard container holds a rotating container (rotaingDiv), which then holds a child element (crosshair). I would like to find the x and y positions in relation to the dartboard container. Here is what I have at present:
$('#dartboard').append( $('#rotatingDiv').append( $('#crosshair') ) );
X = $('#crosshair').position().left.toFixed(1)
Y = $('#crosshair').position().top.toFixed(1)
console.log("x is "+X+", y is "+Y);
This process runs within a per-second timer, upon inspection of the x and y values, I've noticed that i'm only receiving this information in relation of the crosshair element being inside the rotatingDiv instead of being at the dartboard level (parent of parent). Does anyone know how I can do this?
Try this:
var parentLeft = $('#parent').offset().left,
parentTop = $('#parent').offset().top
childLeft = $('#child').offset().left,
childTop = $('#child').offset().top;
// Positions respective to parent
var top = parentTop - childTop,
left = parentLeft - childLeft;
You can also use position.
This should work:
var pos1 = $("#crosshair").position();
var pos2 = $("#crosshair").parent().position(); // or $('#rotatingDiv').position();
var x = (pos1.left + pos2.left ).toFixed(1);
var y = (pos1.top + pos2.top ).toFixed(1);
Be careful:
Note: jQuery does not support getting the position coordinates of
hidden elements or accounting for borders, margins, or padding set on
the body element.
You can check the API here.

Javascript get absolute position of a div

I have a div (oCell) created at runtime using javascript.
I then want to position another independant div (random-div) relative to this div. For reasons within the program random-div has to be positioned absolutely and oCell relatively. The oCell div is positioned relative as it is within a table.
My problem is I need to find the absolute position of the oCell div, rather than the relative position.
So far I have:
var oCell = document.createElement("td");
var height = oCell.getBoundingClientRect().top;
var right = oCell.getBoundingClientRect().right;
oCell.oBoxPositionTop = height;
oCell.oBoxPositionSide = right;
But from what I can understand, this is returning the relative height of oCell div, which is in turn not positioning random-div in the correct place.
The getBoundingClientRect gives coordinates in viewport coordinates (or coordinates relative to the visible content shown in your browser window). With absolute positioning, you need document coordinates. To convert viewport coordinates to document coordinates, add the scroll offsets of the page to the left and top values returned by getBoundingClientRect:
//technique used in JavaScript: Definitive Guide
var scrollOffsets = (function () {
var w = window;
// This works for all browsers except IE versions 8 and before
if (w.pageXOffset != null) return {x: w.pageXOffset, y:w.pageYOffset};
// For IE (or any browser) in Standards mode
var d = w.document;
if (document.compatMode == "CSS1Compat")
return {x:d.documentElement.scrollLeft, y:d.documentElement.scrollTop};
// For browsers in Quirks mode
return { x: d.body.scrollLeft, y: d.body.scrollTop };
}());
//Your code:
var oCell = document.createElement("td");
//changed from height to top and gets document coordinates of position
var top = oCell.getBoundingClientRect().top + scrollOffsets.y;
//changed from right to left
var left = oCell.getBoundingClientRect().left + scrollOffsets.x;
oCell.oBoxPositionTop = top;
oCell.oBoxPositionSide = left;

how do i get the x and y position directly under the left bottom side of the input rectangle?

I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>

Get position of map area(html)?

Is this possible? I'm trying to find the x and y coordinates of the element in relation to the browser.
var position = $(this).position();
x = position.left;
y = position.right;
Doesn't work.
Is there any way to do this?
http://adamsaewitz.com/housing/
highlight the blue room 070
The problem lies in the fact that you are accessing the top/left of an area element.
The area element is not positioned where its coords say. This is handled behind the scenes by the dom/browser.
So you need to find the image that the area relates to and grab its offset.
var imgId = $(this).closest('map').attr('name');
var imgPos = $('#' + imgId).offset();
Then, you grab the coords attribute of the area and split it to get left/top/width and use those to pinpoint the location inside the image.
var coords = $(this).attr('coords').split(',');
var box = {
left: parseInt(coords[0],10),
top: parseInt(coords[1],10),
width: parseInt(coords[2],10)-parseInt(coords[0],10),
height: parseInt(coords[3],10)-parseInt(coords[1],10)
};
Take into consideration the width/height of the info box that appears (and since you animate it, take that into consideration as well) and you get to
x = imgPos.left + box.left + box.width/2 - 65; // 65 is the info width/2
y = imgPos.top + box.top -20 -160 -1; // 20 is the animation, 160 is the info height, 1 is a safe distance from the top
demo: http://www.jsfiddle.net/XBjwN/
Edit for updated question: Since you're using <area> it's a different story, and fetching from the coords attribute is much easier, like this:
var position = $(this).attr('coords').split(',');
x = +position[0] - 50;
y = +position[1] - 170;
The offsets are just to account for the hard-coded width/height of the tooltip itself. In addition to the above, you want to use top and left rather than margin-top and margin-left. Also to account for the #content <div>'s position in the page, give it a relative position for the tooltip to sit in, like this:
#content { position: relative; }
Then...instead of .after(), use .append() so it gets added inside that parent.
You can test the result here.
For original question:
The object .position() returns has top and left properties...but you want .offset() here anyway (it's relative to the document, where .position() is relative to the offset parent), so it should look like this:
var position = $(this).offset(),
x = position.left,
y = position.top; //not right!
Or this:
var position = $(this).offset();
var x = position.left;
var y = position.top;
...but without a single var comma-separated statement, or a var on each line, you're also creating (or trying to) global variables, which will blow up in IE.
$(document).ready(function () {
$('map').imageMapResize();
$('area').hover(function () {
$('.imgpopover').css({ "display": "block", "top": $(this).attr("coords").split(',')[1]+"px", "left": $(this).attr("coords").split(',')[0]+"px" })
$('.imgpopover label').text($(this).attr("title"))
}, )
});

Categories

Resources