JS - check if element's declared style property is set in vh - javascript

Say we have an element
<div class="vh-100">
Content
</div>
.vh-100 { height: 100vh }
How can I get to read that exact value 100vh, because
var computedHeight = window.getComputedStyle(element).height; // will simply return the `window.clientHeight` value in pixels in this case.
var styleAttributeHeight = element.style.height // will return '', which is empty
To put it simply, I need to find a way to determine if the value is set in vh because the child elements of the example <div class="vh-100"> have the box model broken and return incorrect offsetTop and offsetLeft for some reason.
I need a simple solution excluding checking the rules in the CSS file.
Here is a link to hopefully explain why I need this.

Directly no way, but i convert pixels to vh(1vh is 1/100 browser height). Here is code snippet, i hope it will help you.
/*var z = getComputedStyle(document.getElementsByClassName('deneme')[0],null).height.replace('px','');*/
/*var b = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);*/
//deactive variables for detailed usings.
var a = document.getElementsByClassName('sample')[0].clientHeight;
var b = window.innerHeight;
var c = Math.round((a / b) * 100) + "vh";
console.log(a)
console.log(b)
console.log(c)//it's your "vh"
.sample{
width: 10vw;
height: 1vh;
background:dodgerblue;
}
<div class="sample"></div>

if what you want is the unit of the height
yourElement.style.height
Normally it will return a string of height in it unit that you settled for the element (so '100vh' in your case).

Related

Equivalent to setting html and body height to window height in vanillajs

What is the equivalent code in vanilla js to this line of javascript?
$('html, body, #wrapper').height($(window).height());
This was my attempt, but it doesn't seem to be working properly (it seems to not set any height on all 3 elements at all):
var w=window,d=document,
e=d.documentElement,
g=d.getElementsByTagName("body")[0];
x=w.innerWidth || e.clientWidth || g.clientWidth,y=w.innerHeight || e.clientHeight || g.clientHeight;
document.querySelector("html").clientHeight = g.clientHeight = document.getElementById("wrapper").clientHeight = y;
You can get the height of the window using Window#innerHeight, select the target using Document#querySelectorAll. To iterate the elementList that querySelectorAll returns, we'll use NodeList#forEach (if not supported convert the element list to an array - see below), and set the height on each element:
var height = window.innerHeight + 'px';
document.querySelectorAll('html, body, #wrapper').forEach(function(el) {
el.style.height = height;
});
#wrapper {
background: red;
}
<div id="wrapper"></div>
If you need to convert the the element list to an array:
[].slice.call(document.querySelectorAll('html, body, #wrapper'), 0)
or
Array.from(document.querySelectorAll('html, body, #wrapper'))

Extend Existing CSS style by percent- % using JQuery

I am trying to extend an existing css style by 1%, using the following code, but instead its being increment in pixels instead of %.So instead of giving - 7%, its giving me it as 7px.
$("#label").css("top", "+=1%");
The top most div is of size - width: 100%; and the label top : 6% which is already defined.
Any idea/suggestion on this would be really helpful
You can try to get the current top property value, and then add 1%;
var currentTop = $("#label").css("top");
var topAdded = parseInt(currentTop.replace("%","")) + 1;
$("#label").css("top", topAdded + "%");
You can do this:
var top = parseInt($("#label").css("top").replace("%", ""));
top ++;
$("#label").css("top", top+"%")
Update:
For one line statement you can do this:
$("#label").css("top", (parseInt($("#label").css("top").replace("%", "")+1)+"%")

jQuery window width not equal to CSS's window width

I'm using the following two pieces of CSS and JS code:
#media (max-width: 720px) {
// a code to make arrows in a carousel disappear
}
if(jQuery(window).width() <= 720){
// a code to make arrows in the carousel stop working
}
The problem with them is that the latter executes on exactly width=738px and not 720px. I suspect that this is because of browser's vertical scrollbar that has width equal to 18px in Chrome.
Is there a way to unify this? I'd like these actions to happen at the same moment in all browsers regardless of the scrollbar's width.
Tests (when browser is # 720px and CSS has already executed):
jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703
I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:
Add a hidden element to your page,
Use media queries to alter the max-width property of that element,
Read back the max-width property of that element through Javascript.
For instance, add the following element to your page:
<div id="currentMedia"></div>
Then write the following CSS rules:
#currentMedia {
display: none;
}
#media (max-width: 720px) {
/* Make arrows in the carousel disappear... */
#currentMedia {
max-width: 720px;
}
}
Then, from the Javascript side, you can write:
if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
// Make arrows in the carousel stop working...
}
And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.
I tested this solution on all major recent browsers, and it gives correct results.
You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org.
Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.
innerWidth documentation
innerWidth() says this method is not applicable to window and document objects; for these, use .width()
try
How can I get the browser's scrollbar sizes?
From Alexandre Gomes Blog
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
in your code
if(jQuery(window).width()-getScrollBarWidth(); <= 720){
// a code to make arrows in the carousel stop working
}
A bit outdated thread, but i've found this solution
function getWidth(){
return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}
If you are using Bootstrap > 3 then I will suggest you something.
Bootstrap ships with .container class in its Css and predefined. And its altering with #media queries.So my working code sample for this is below.
function detectWidth(){
var width = $('.container').eq(0).outerWidth() ;
console.log(width);
if(width<750){
// do something for XS element
}else if(width>=750 && width<970){
// do something for SM element
}else if(width>=970 && width<1170){
// do something for MD element
}else{
// do something for LG element
}
}
I realize this is an old thread, but I think it can still benefit from this answer.
var width = window.outerWidth;
This will give you the width of the window including scrollbars, which is what media queries use, I believe.

Modify external CSS values

Hi I am trying to dynamicly change the height of a division using JavaScript but I can only get the JS to read the Height element of the div if it defined using style tags inside the HTML mark-up.
If its in a separate sheet it returns NaN, I'm assuming because it can't find a value and is actually returning null (I'm using ParseInt to make it work).
Here is the HTML:
<div id="dropdown_container">
<div id="dropdown" style="height:100px;">
a
</div>
</div>
(Wish the HTML stlye markup)
And here is the JS:
function clickDown() {
var el = document.getElementById('dropdown');
var maxHeight = 200;
getHeight = parseInt(el.style.height.substring(0,(el.style.height.length)-2));
console.log(getHeight);
getHeight += 2;
el.style.height = getHeight + 'px';
timeoutHeightInc = setTimeout('clickDown()',15);
if(getHeight >= maxHeight){
clearTimeout(timeoutHeightInc);
}
}
Does anyone know of a reason for this (mis?)functionaility. And a solution for it?
Here is a jsFiddle.
Try moving the height over to the CSS to see the issue i'm having.
ParseInt is missing it's radix.
You say:
I can only get the JS to read the Height element of the div if it
defined using style tags inside the HTML mark-up
Now you are only reading the div's attribute style. Which you set inline. So if you remove that, than you can not read it anymore. Make sense?
You want to get the computed height. Try: .offsetHeight
Basis of test-case to play with inc. fixed radix. this fiddle
UPDATE: tada: fixed, see this updated fiddle
function clickDown() {
var el = document.getElementById('dropdown');
var maxHeight = 200;
getHeight = parseInt(el.offsetHeight,10);
console.log(getHeight);
getHeight += 2;
el.style.height = getHeight + 'px';
timeoutHeightInc = setTimeout('clickDown()',15);
if(getHeight >= maxHeight){
clearTimeout(timeoutHeightInc);
}
}

How to convert pixels to em in a easy way

I am looking for a easy way to add a line of code to a plugin of mine, to convert a couple of pixel values into em values, because the layout of my project needs to be in ems. Is there an easy way to do this, because I don't want to add a third-party plugin to the site.
Won't post the code here, as it has nothing to do with the plugin it self.
Example: 13px -> ??em
I think your question is very important. Since the classes of display resolutions are rapidly increasing, using em positioning to support wide range of screen resolutions is a really appealing approach. But no matter how hard you try to keep everything in em -- sometimes you get a pixel value maybe from JQuery drag and drop or from another library, and you would want to convert this value to em before sending it back to server for persistence. That way next time user looks at the page, item would be in correct position -- regardless of screen resolution of the device they are using.
JQuery plugins are not very scary when you can review the code, specially if they are short and sweet like this plugin to convert pixel values to em as you want. In fact it is so short I will paste the whole thing here. For copyright notice see the link.
$.fn.toEm = function(settings){
settings = jQuery.extend({
scope: 'body'
}, settings);
var that = parseInt(this[0],10),
scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;"> </div>').appendTo(settings.scope),
scopeVal = scopeTest.height();
scopeTest.remove();
return (that / scopeVal).toFixed(8) + 'em';
};
$.fn.toPx = function(settings){
settings = jQuery.extend({
scope: 'body'
}, settings);
var that = parseFloat(this[0]),
scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;"> </div>').appendTo(settings.scope),
scopeVal = scopeTest.height();
scopeTest.remove();
return Math.round(that * scopeVal) + 'px';
};
Usage Example: $(myPixelValue).toEm(); or $(myEmValue).toPx();.
I just tested this in my application, it works great. So I thought I share.
The following seems to do as you require, though it's based on the font-size of the parent, and of the element itself, being returned in px:
function px2em(elem) {
var W = window,
D = document;
if (!elem || elem.parentNode.tagName.toLowerCase() == 'body') {
return false;
}
else {
var parentFontSize = parseInt(W.getComputedStyle(elem.parentNode, null).fontSize, 10),
elemFontSize = parseInt(W.getComputedStyle(elem, null).fontSize, 10);
var pxInEms = Math.floor((elemFontSize / parentFontSize) * 100) / 100;
elem.style.fontSize = pxInEms + 'em';
}
}
JS Fiddle proof of concept.
Notes:
The function returns false, if the element you're trying to convert to em is the body, though that's because I couldn't work out whether it was sensible to set the value to 1em or simply leave it alone.
It uses window.getComputedStyle(), so it's not going to work with IE, without some adjustments.
References:
Math.floor().
parentNode.
parseInt().
tagName.
toLowerCase().
window.getComputedStyle().
Pixels and ems are fundamentally different types of unit. You can't simply convert between them.
For instance, a user with a default font size of 16px on a site where top-level headings are styled at 200% font size, 1em may be equal to 32px. Move the heading elsewhere in the document, it could be 64px or 16px. Give the same document to a different user, it might be 30/60/15px. Start talking about a different element, and it can change again.
The closest you can come to what you want is to convert from pixels to ems+document+context+settings. But if somebody has asked you to lay out your project with ems, they will probably not be pleased that you are trying to do it in pixels then "converting".
Usually when you want to convert px to em, the conversion happens on the element itself. getComputedStyle returns value in px which break their responsiveness. The code below can be used to help with this issue:
/**
* Get the equivalent EM value on a given element with a given pixel value.
*
* Normally the number of pixel specified should come from the element itself (e.g. element.style.height) since EM is
* relative.
*
* #param {Object} element - The HTML element.
* #param {Number} pixelValue - The number of pixel to convert in EM on this specific element.
*
* #returns {Boolean|Number} The EM value, or false if unable to convert.
*/
window.getEmValueFromElement = function (element, pixelValue) {
if (element.parentNode) {
var parentFontSize = parseFloat(window.getComputedStyle(element.parentNode).fontSize);
var elementFontSize = parseFloat(window.getComputedStyle(element).fontSize);
var pixelValueOfOneEm = (elementFontSize / parentFontSize) * elementFontSize;
return (pixelValue / pixelValueOfOneEm);
}
return false;
};
Using it would be as simple as:
var element = document.getElementById('someDiv');
var computedHeightInEm = window.getEmValueFromElement(element, element.offsetHeight);
Old question, but for reference, here is something I cobbled together, scope and suffix are optional. Pass it a rem or em value as string, eg. '4em' [ you can use spaces and upper/lowercase ] and it will return the px value. Unless you give it a scope, which would be the target element for finding the local EM value, it will default to body, effectively giving you the rem value. Lastly, the optional suffix parameter [ boolean ] will add 'px' to the returned value such that 48 becomes 48px for example.
ex: emRemToPx( '3em', '#content' )
return 48 on a font-size 16px / 100% document
/**
* emRemToPx.js | #whatsnewsisyphus
* To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
* see CC0 Public Domain Dedication <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
var emRemToPx = function( value, scope, suffix ) {
if (!scope || value.toLowerCase().indexOf("rem") >= 0) {
scope = 'body';
}
if (suffix === true) {
suffix = 'px';
} else {
suffix = null;
}
var multiplier = parseFloat(value);
var scopeTest = $('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;"> </div>').appendTo(scope);
var scopeVal = scopeTest.height();
scopeTest.remove();
return Math.round(multiplier * scopeVal) + suffix;
};
I've packaged this functionality into a library, complete with parameter type checking: px-to-em
Given this HTML:
<p id="message" style="font-size: 16px;">Hello World!</p>
You can expect these outputs:
pxToEm(16, message) === 1
pxToEm(24, message) === 1.5
pxToEm(32, message) === 2
Since the OP requested a way to do this without a library, I've copied the source code of px-to-em to a live demo:
function pxToEm (px, element) {
element = element === null || element === undefined ? document.documentElement : element;
var temporaryElement = document.createElement('div');
temporaryElement.style.setProperty('position', 'absolute', 'important');
temporaryElement.style.setProperty('visibility', 'hidden', 'important');
temporaryElement.style.setProperty('font-size', '1em', 'important');
element.appendChild(temporaryElement);
var baseFontSize = parseFloat(getComputedStyle(temporaryElement).fontSize);
temporaryElement.parentNode.removeChild(temporaryElement);
return px / baseFontSize;
}
console.log(pxToEm(16, message), 'Should be 1');
console.log(pxToEm(24, message), 'Should be 1.5');
console.log(pxToEm(32, message), 'Should be 2');
<p id="message" style="font-size: 16px;">Hello World!</p>
I learned from this answer that with getComputedStyle we can reliably obtain the divisor px value with the decimal point, which improves the accuracy of the calculation. I found that the answer by Aras could be off by over 0.5px, which caused rounding errors for us.
Try using this:
parseInt(myPixelValue) / parseFloat($("body").css("font-size"));
Ems don't equal pixels in anyway. They are a relative measurement.
<span style="font-size: 1em;">This is 1em font size, which means the text is the same size as the parent</span>
<span style="font-size: 1.5em;">This is 1.5em font size, which means the text is 150% the size as the parent</span>
The base size is determined by the user-agent (browser).

Categories