(programmatic) Position of divs, what property should one use? - javascript

I would like to get/set the position of divs. I don't know what's the best technique one should use:
The CSS style?
var x = aDiv.style.left;
var y = aDiv.style.top;
or use the HTML div element's clientTop/clientLeft?
or... ?
Thanks for your time!
J.

clientTop and clientLeft are read-only, so you can't set the div position with them. There are multiple ways to do it with CSS, I suggest you study the basics of CSS positioning.

Related

Can I use JS .offsetHeight result in equation to style child element?

Thanks for reading this.
I'm trying to obtain the .offsetHeight of a parent element, so that I can use it to automatically adjust the margin of a child element to align things properly.
Is it possible to apply a result from .offsetHeight into an equation?
Thank you!
Yes, use .parentElement.offsetHeight
E.G:
document.getElementById('post-form').parentElement.offsetHeight;

Changing <div> CSS attributes

I have a <div> element reference in JavaScript as follows:
custom_div = document.createElement("div")
I want to change the position of this element to absolute and set the bottom alignment to 0, through JavaScript. I am looking for suggestions.
There are SO many ways to do this, but direct manipulation of DOM is not recommended. Either use CSS classes or try jQuery.
You can simply use:
document.getElementById("div#example").style.position="absolute";
document.getElementById("div#example").style.bottom="0";

jQuery or JavaScript get element near other element

How (using either jQuery, or JavaScript...)
<div style="background-color:red;height:10px;width:10px;float:left;"></div>
<div style="background-color:red;height:10px;width:10px;float:left;margin-left:25px;"></div>
<br>
<div style="background-color:red;height:10px;width:10px;margin-left:15px;" id="2">
Do I get what element is closest to id=2? I need this type of selector, and any help would be appreciated. :)
Note that I don't mind setting a position:relative or absolute and left:(number)px to these elements.
I need a code that would work in a dynamic environment; you know, when blocks keep getting created and keep scrolling forwards and changing left position. Could I use .position() perhaps? Somehow?
Thank you. :)
That's a fun thought experiment...
To solve this, you'd probably want to calculate the offset of each element, and compare those coordinates (top and left) to other elements.
Assuming you want to find the element closest to compareEl, and you have compareElTop and compareElTop, loop through all elements on screen (except compareEl), and do something like this:
var topDiff = Math.abs(compareElTop-elements[x].offset().top);
leftDiff = Math.abs(compareElLeft-elements[x].offet.left);
Pair with the lowest topDiff+leftDiff is closest.
Here is a nice jsFiddle for you to play around with! All kinds of awesome.
For example if you want to get DOM elements that is closest with #2:
<span>before</span>
<div style="background-color:red;height:10px;width:10px;margin-left:15px;" id="2"> </div>
<span>after</span>
Javascript:
$(function(){
var prevIt = $('#2').prev();
var nextIt = $('#2').next();
});
Here is demo

How to get the line height of a span?

Is there a way to get the line-height of a span (or other inline element) in JavaScript/jQuery?
I need the exact computed line-height in pixels, not values of the sort 1.2em, normal or heuristics like fontSize * 1.5.
What I need to do is stretch the background of a span to fill the whole height of the line. I figured that I could add paddings to stretch the span, but for this I need the exact line-height. If someone can offer another approach, this would also be helpful.
An easy way to do this is:
var style = window.getComputedStyle(element);
var lineHeight = style.getPropertyValue('line-height');
This will get the calculate value of the line height without using jQuery and works on all browsers from IE9 onwards.
$("span").css( "line-height");
Retrieves the computed px value as a string "16px" for example. It uses IE's currentStyle or the standard getComputedStyle under the covers. Which is kind of surprising seeing as when it works as a setter it does elem.style.something = value which is a whole different thing.
assuming that the span is contained in a div.
you could set the div to position:relative
and the span as a block that takes 100% height.
In this way you will stretch the span as you want.
Example here
(note: to see the effect, change the background colour of the span to transparent. You should be able to see the red div.)
If your design allows for it, you can apply inline-block to the elements you are targeting and then use outerHeight ...
var inlineHeight = $('.inline-height').css("display", "inline-block").outerHeight();
//console.log('Inline Height:' + inlineHeight);

How to get the bounding box of a wrapping inline element with prototype

I used to use cumulativeOffset() and getDimensions() to calculate the bounding box of elements, but just realized that cumulativeOffset returns the top left corner oft the start of an element. Meaning: if an inline element wraps, and the next line is more to the left than the start, I get a displaced bounding box.
After researching a bit, I found that I can use getClientRects() to get all rects. I could then go through, and just take the left position of the rect that's most to the left.
I was wondering if there is a better way of doing this... I just didn't find a boundingBox() prototype function. Did I overlook it?
Edit: I also just found out that getClientRects() is not supported by all browser, so this is no solution.
I don't see a boundingBox() function either, but I wonder if using the same technique (cumulativeOffset() and getDimensions()) on the parent via: getOffsetParent() would do what you want. getOffSetParent():
"Returns element’s closest positioned
ancestor. If none is found, the body
element is returned."
Which should account for word-wrapping where the second line is further left.
I've never heard of a way to do this. You could set it position:relative, drop a 1x1 absolutely positioned div into it, position it right:0, get that div's LEFT + WIDTH, and subtract the offset width of the original inline item from that value.
Saying that, total hack, maybe you need to rethink the reason you want to do this!
The solution given by dfitzhenry seems not working in the case of multiline inline elements.
Here's my Javascript solution : get your inline element nextSibling, check if it is an inline element, otherwise create a new inline element, add it to your inline element's parent and then get its offsetLeft:
var parentContainer = inline_elm.parentNode;
var nextsib = inline_elm.nextSibling;
var remove_next_sibling = false;
if(!nextsib || nextsib.clientWidth != 0){
remove_next_sibling = true;
var temp= document.createElement('span');
parentContainer.insertBefore(temp, nextsib);
nextsib = temp;
}
var inline_bounding_right = nextsib.offsetLeft;
if(remove_next_sibling) parentContainer.removeChild(nextsib);
This is an old post, but the standard method now to get a bounding box is getBoundingClientRect(), which is supported in all major browsers and has had at least partial support since 2009 in most browsers. Enjoy!
P.S. getClientRects() is also very useful for getting the individual bounding boxes of the wrapped text. It seems to have the same browser support as getBoundingClientRect(), since the one depends on the other, and this source suggests that it's well supported.

Categories