Getting coordinates of objects in JS - javascript

So based on this question I asked, what's the most reliable way of getting position of objects that's crossbrowser? Thx

In general, assuming you have an element named elem, it's actually quite easy to get the X and Y coordinates of the top-left corners of an element, assuming you want these in document coordinates. In all browsers this is returned by the elem.offsetLeft and elem.offsetTop properties.
The only trick you have to be aware of is that if elem is absolutely positioned in another element, say a div with a left / top margin of 20px, these properties will return 0, as it only takes into account the current element and not the entire chain of elements. Luckily we can use a "chain-traversal" function to capture all of the margins of elements associated with a given element, tally them up to get the correct document coordinates.
As Sime Vidas mentioned, there is also JQuery's position() and offset() properties, in this case you would want the offset() properties.
You can also use the getBoundingClientRect() method, however this returns the coordinates of an element relative to its offsetParent and thus is not entirely reliable. Look at the following examples:
// getPosition function
function getPosition(elem){
var dims = {offsetLeft:0, offsetTop:0};
do {
dims.offsetLeft += elem.offsetLeft;
dims.offsetTop += elem.offsetTop;
}
while (elem = elem.offsetParent);
return dims;
}
cont1.style.position = "absolute";
cont1.style.marginLeft = "10px";
cont2.style.position = "absolute";
cont2.style.marginLeft = "10px";
box.style.position = "absolute";
box.style.marginLeft = "10px";
console.log(getPosition(box).offsetLeft); // returns "30"
console.log(getPosition(box).offsetTop); // returns "0"
// or in JQuery
console.log($(box).offset().left) // also returns "30"
console.log($(box).offset().top) // also returns "0"
Also I suggest you read this.

If you want to find the position of an element relative to document use jQuery offset() method.
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
.offset() reference: http://api.jquery.com/offset/
If you want to find the poistion of an element relative to its parent then use jQuery position() method.
var p = $("p:first");
var position = p.position();
$("p:last").text( "left: " + position.left + ", top: " + position.top );
.position() reference: http://api.jquery.com/position/
And these methods almost gives perfect result in most of the browsers.

I like element.getBoundingClientRect(). It has good cross-browser support.
var coords = element.getBoundingClientRect();
This gives the coordinates relative to the viewport. To get the coordinates relative to the document, add document.documentElement.scrollTop to the top and document.documentElement.scrollLeft to the left.
coords.top += document.documentElement.scrollTop;
coords.left += document.documentElement.scrollLeft;
But since you are already using jQuery, you may as well just use .offset().

Related

How to get distance between two divs

So I have one div inside the other - how can I get distance between them?
I tried something like $('#child').parentsUntil($('#parent')).andSelf() - but it returns an object, not a distance.
P.S. I need it to push other buttons.
http://api.jquery.com/position/
to get the left distance you can use:
var distLeft = $('#child').position().left;
That will return the distance in px relative to the offset parent
if you're interested into the element's page offset than:
var offsLeft = $('#child').offset().left;
http://api.jquery.com/offset/
There's this awesome getBoundingClientRect function. Anything else is just a-b
https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect
You can use offset
var childOffset = $('#child').offset(), parentOffset = $('#child').parentsUntil($('#parent')).offset();
var leftDistance =childOffset.left - parentOffset.left;
var topDistance = childOffset.top- parentOffset.top;
Did you try something like?
$('innerDiv').position().left;

Using JavaScript to increment top/left/bottom/right values

I am trying to increment the position of an element by, say, x pixels. Here is what I've tried so far:
var top = document.getElementById("something").style.top;
top = top + "300px"
I know that this is not going to work, but I was wondering if it was possible to increment a position value like this.
Because style.top is a string with units on the end of it like "300px" you can only do math with it when you convert just the numeric part to an actual number.
Assuming you have a positioned element (so setting the top value will do something) and you already have a top style set directly on the element and not set via CSS (so getting obj.style.top will actually get you something), you can do it by parsing the number out of the style value like this:
var obj = document.getElementById("something");
var topVal = parseInt(obj.style.top, 10);
obj.style.top = (topVal + 300) + "px";
Working example: http://jsfiddle.net/jfriend00/pt46X/
That won't work fine because, for example, if top had a value of 200px, it would become "200px300px". Try this:
var elem = document.getElementById("something");
elem.style.top = parseInt(elem.style.top, 10) + 300 + "px"
Demo WEEEE!!!!
let top = 0;
let left = 0;
let text = document.getElementById("TextToTranslate");
text.setAttribute("style","top:"+top+"px; "+left+":px;");
use this in a while loop and it works fine, i'm just figuring out how to slow it down so i can see the transition

Using javascript, how to get the position of an element

like the title says, how to get the element's x, y positions with respect to their location in the web page and their positioning schemes like absolute, relative etc.
In a modern browser, getBoundingClientRect and getClientRects will give you rect objects describing your element. See https://developer.mozilla.org/en/DOM/element.getBoundingClientRect and https://developer.mozilla.org/en/DOM/element.getClientRects
If you have to work with IE8, then you'll have to do different things in different browsers to get correct answers (e.g. object-detect getBoundingClientRect and fall back on some other method if it's not present).
The jQuery offset() calculation and the Quirksmode findPos will give incorrect answers in any browser that does subpixel positioning (e.g. Firefox or IE9), because they will round the answer to an integer number of pixels. Depending on what you're doing, that may or may not be ok.
With jQuery:
var $elt = $('select an element however'),
cssPosition = $elt.css('position'),
offset = $elt.offset(),
top = offset.top,
left = offset.left;
Without jQuery, use Quirksmode's findPos function:
var elt = document.getElementBy...,
pos = findPos(elt),
top = pos[1],
left = pos[0];
Getting the computed CSS position value without a library is another can of worms. It boils down to:
element.currentStyle (IE)
getComputedStyle(element) (real browsers)
Check out this
JS:
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
HTML:
<div id="ser"> TEST</div>
RETURN CALL:
alert(findPos(document.getElementById('ser')));
I hope its help to you

How to get content currently being displayed in browser viewport

How can I get an indication of what part of a long document is currently being displayed?
E.g. if my html contains 1,000 lines
1
2
3
...
999
1000
and the user is near the middle showing the 500th line then I would like to get "500\n501\n502" or something like that.
Obviously most scenarios would be more complex than this, but my requirement is to find which text is currently being displayed in the browser viewport so I can show a status value appropriate to the current text.
Thanks
Martin
If you have jQuery, you can use this function to check if a DOM element is currently shown in the viewport:
function isInView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
You can get a value in pixels from the scrollTop property:
document.body.scrollTop = 40;
To know what part of your document that is visible, you could loop through (say) all p-tags until you find one with a negative scrollTop value. The one before that is the one at the top of the window.
I've just seen a piece of sample code on msdn
function isinView(oObject)
{
var oParent = oObject.offsetParent;
var iOffsetTop = oObject.offsetTop;
var iClientHeight = oParent.clientHeight;
if (iOffsetTop > iClientHeight) {
alert("Special Text not in view. Expand Window to put Text in View.");
}
else{
alert("Special Text in View!");
}
}
Yes, there is a way. I will use YUI's API to illustrate my example. First your text must be in some sort of dom element, whether its a span, div, p or anything, it must be in a element. Here I will assume list item
var viewPortY = YAHOO.util.Dom.getDocumentScrollTop(),
viewPortHeight = YAHOO.util.Dom.getViewportHeight(), i = 0,
// get all the dom elements that contain the text, sorry if this isn't exact, its just a rough example
items = YAHOO.util.Dom.getElementBy(null, 'li', document.getElementById('item-container')),
viewedItems = [];
for (i = 0 ; i < items.length; i++) {
var y = YAHOO.util.Dom.getY(items[i])
if (y > viewPortY && y < (viewPortY + viewPortHeight)) {
viewedItems.push(items[i])
}
}
So essentially, I get all the dom objects that contain the text your interested in. I then loop through, and whoever's Y co-ordinate is between the viewports Y and Y + ViewPort Height, I put in an array.
I implemented what I thought was a more optimal solution for my environment:
I am writing for Android so I can easily interact with a Java class from javascript. My actual solution involved getting offsetTop of all tags I am interested in and passing the offsets to java.
Also registering an onscroll handler that passed window.pageYOffset throught to the same Java class. Then the java class can compare offsetTop of each tag with pageYOffset to see which tag is at the top of the current viewport.

Getting offsetTop of element in a table

I can't seem to figure out how to get the offsetTop of an element within a table. It works fine on elements outside tables, but all of the elements within a table return the same result, and it's usually at the top of the page. I tried this in Firefox and Chrome. How do I get the offsetTop of an element in a table?
offsetTop returns a value relative to offsetParent; you need to recursively add offsetParent.offsetTop through all of the parents until offsetParent is null. Consider using jQuery's offset() method.
EDIT: If you don't want to use jQuery, you can write a method like this (untested):
function offset(elem) {
if(!elem) elem = this;
var x = elem.offsetLeft;
var y = elem.offsetTop;
while (elem = elem.offsetParent) {
x += elem.offsetLeft;
y += elem.offsetTop;
}
return { left: x, top: y };
}

Categories

Resources