How to get distance between two divs - javascript

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;

Related

Get Computed Height - Javascript - Not jQuery

I have two divs side by side set to height auto. I want them to have equal height, so i combined them as members of an array.
I recurse through the array and set the not-tallest ones to the height of the tallest. Problem is everything i have tried to get the COMPUTED height has resulted in the incorrect value.
I have tried the following:
(els[x].currentStyle) ? h=els[x].currentStyle.height : h=window.getComputedStyle(els[x],null).height;
h = el.clientHeight || el.offsetHeight || el.scrollHeight;
Both of these are yielding 640 px'ish while the computed is 751.8 in my particular showing.
Is there possbily a constant I can use to get the correct height. Like maybe the number im getting would be on a standard size screen (like 960 pixels high or such) then multiple that by the window size?
I have had a lot of good use of this little function I came up with
function getH(id)
{
return document.getElementById(id).offsetHeight;
}
// I have a styles.js file where this function feels right at home. Access this function from anywhere.
This will return the height of any given elements given to the function (by it's ID). So now we'r 1/3 of the way.
Then use the Math.max() function to get the height of the largest element.
var maxH = Math.max(getH("ID1"),getH("ID2"));
This is 2/3 of the way, YAY - Now set the elements height to be the same.
var x = document.getElementById("ID1");
var y = document.getElementById("ID2");
x.style.height = maxH +"px";
y.style.height = maxH +"px"; //Remember the +"px" has to be added as a string, thats the reason for the "".
DONE!! - Now put it all together
I would imagine something like this
function setElementHeight()
{
var maxH = Math.max(getH("ID1"),getH("ID2"));
var x = document.getElementById("ID1");
var y = doc...("ID2");
x.style.height = maxH +"px";
y.style.height = maxH +"px";
}
// Don't forget to include the first function in you'r .js file
This WILL set both ID's to the same height and the height WILL be equal to the highest. That is what you want, isn't it?
--EDIT--
I would throw away the array if I were you. Just have the 2 DIV's each with a unique ID and make them equally tall based upon that.
Molle
If you have the DOM document, you can try the below code:
let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;
'height' will have the exact height of the element with 'divId' once it is computed.

Find distance between two DIVs using jQuery?

I have two DIVs that I need to know the calculated browser distance (in height) of them.
I have read about the offset feature but the examples were not written for the way I am trying to do this.
Example usage:
<div class="foo"></div>
<div class="bar"></div>
I want to know the distance between these two.
Please help me to find the distance dynamically with jQuery.
Something like this should work:
$('.foo').offset().top - $('.bar').offset().top
As long as each class only has one element on the page.
If they are not unique, give the two elements an ID and reference with that.
Use .offset():
$('.foo').offset().top - $('.bar').offset().top
This function finds the distance in pixels between the centre of two elements, no jquery:
function distanceBetweenElems(elem1, elem2) {
var e1Rect = elem1.getBoundingClientRect();
var e2Rect = elem2.getBoundingClientRect();
var dx = (e1Rect.left+(e1Rect.right-e1Rect.left)/2) - (e2Rect.left+(e2Rect.right-e2Rect.left)/2);
var dy = (e1Rect.top+(e1Rect.bottom-e1Rect.top)/2) - (e2Rect.top+(e2Rect.bottom-e2Rect.top)/2);
var dist = Math.sqrt(dx * dx + dy * dy);
return dist;
}
I use it like this:
var target1 = document.querySelector('#foo');
var target2 = document.querySelector('#bar');
if (distanceBetweenElems(target1,target2)<100){
target1.classList.add('active');
}

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

Getting coordinates of objects in JS

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().

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.

Categories

Resources