Get Computed Height - Javascript - Not jQuery - javascript

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.

Related

Get the smallest side of a user device screen size JS/jQuery

I want to get user device display size with screen.width and screen.height on page load (for example: iPhone 7, 375x667px), then I need to compare these two sizes and use the smallest size (375px) to apply it to an element with CSS function.
function() {
var ww = screen.width;
var wh = screen.height;
}
I'm new to JavaScript so don't know how to do the second part, comparison and further manipulation.
How can it be done?
As said in comments by many people, we can't understant why not to use if.
You could have used conditional operators: ? and :, but it is in essentially an if.
You can also make use of the Math library with min() or max() functions to get the smallest or highest value of some values (can be used for arrays also, but it is not the case here). The usage: Math.min(value1, value2)
Example:
var ww = 100;
var wv = 120;
var smallest = Math.min(ww,wv);
console.log(smallest)
Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
To finish, Math.min() or max() also uses if in the internal code...
You can do it like this using jquery,
$(document).ready(function(){
var smallest;
var winwid = $(window).width();
var winheight = $(window).height();
if(winwid < winheight ){
smallest = winwid;
alert('Width is smaller than height: '+winwid);
}
else {
smallest = winheight;
alert('Height is smaller than width: '+winheight);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Computing minimum of two lengths in JavaScript

I need to set for a div a margin-left in JavaScript in such a way that its value if the minimum between two lengths in different units, e.g. min(10pt,15vw).
There is Math.min() that we can use to compare numbers. Is there a similar function for lengths?
Alternatively, is there a way to convert length from one unit to another?
The minimum of two lengths with separate units can be calculated by creating a temporary hidden div and using the offsetWidth property to calculate the layout width of the element in pixels (followed by immediate removal of the div):
const minimum = (a, b) => {
const temp = document.createElement('div');
const size = [];
temp.style.padding = 0;
temp.style.border = 0;
temp.style.overflow = 'hidden';
temp.style.visibility = 'hidden';
document.body.appendChild(temp);
temp.style.width = a;
size[0] = temp.offsetWidth;
temp.style.width = b;
size[1] = temp.offsetWidth;
temp.parentNode.removeChild(temp);
return Math.min(size[0], size[1]) - size[0] ? b : a;
};
console.log('The minimum width is:', minimum('100px', '100%'));
As shown above, you can use minimum('100px', '100%') to return the minimum value.
Since 1vw reflects 1% of the viewport's width, you can convert it to pixels using window.innerWidth:
var 1vw = window.innerWidth * 0.01;
and comparing that with 15 pixels:
Math.min(1vw * 15, 10);
You can use simple comparison operators for length comparison like =, <=, >= etc. But only when you have same units. The other part of your questions, you can use a small js library for that, called math.js.
The math.js library comes with support for units. The library does not yet support derived units but that is on the planning.
http://mathjs.org/

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

Javascript style.left is empty string

next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction] is: " ". So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left supposed to return an integer?
Why would this be?
Presumably because it hasn't been set to anything.
Isn't style.left supposed to return an integer?
No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).
See How to get computed style of a HTMLElement if you want to get the computed value for the property rather than what I described in the previous paragraph.
style provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle instead.
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
var lft = document.defaultView.getComputedStyle(el)[direction];
pos = parseFloat(lft);
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
Note: like Elliot said you'll have to get the currentStyle/computedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.
Just a comment.
In your code:
> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;
The split in the first line is superfluous, in the second line parseInt will convert (say) 10px to the number 10 just as effectively (and more efficiently) than what you have.
pos = parseInt(el.style[direction], 10);

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