jQuery .css() returning pixels instead of percent - javascript

Alright, so when I get a CSS property that's been stored as a percent using jQuery .css() it is returned with its pixel value. This is great for my purposes actually, I can use it...is it an intended result I will see consistently in all modern browsers both now and in the future, though?
I can't seem to find much info here. Thanks!

Yes, you can see this behaviour in all browsers both now and in future. Because this is how browsers render the css property. Scripting languages will get these details from the DOM after it got interpreted from the browser. So this is the natural behaviour and this wont change.
Additionally, Percentages will be converted into pixels based on the element's parent during rendering process. So that it will not display the css property in percentage while you retrieving that. You have to calculate it manually if you need it for sure.

From jQuery doc
The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties.
yes it is an intended result
if you want to find the actual style value , you can do something like this,
var topValue = $("#mydiv")[0].style.top

This is covered by the burgeoning CSSOM specification. In general, yes, you can rely on pixel values provided the display property is not set to none. Section 9 of the above has the details; for most properties where you'd expect a number (width and such), it says:
If the property applies to the element or pseudo-element and the resolved value of the 'display' property is not 'none', the resolved value is the used value. Otherwise the resolved value is the computed value.
...where "resolved value" means (for these properties) a number of pixels rather than a relative amount (percentage and similar), which would be the "computed value" ("computed" as in "taking all style rules into consideration").
Supporting the case of this being (newly) specified behavior, when non-pixel values have been returned in various situations, bugs have been reported and accepted (in WebKit, in jQuery, in YUI).

Related

element.style or window.getComputedStyle() does not showing float

I am trying to copy all element style properties, to another element. (both inline and inheritance)
to do so I am using window.getComputedStyle(), but when I am taking all the style values the float value does not exist.
I even tried to use element.style and it not exist there.
but when I am using jQuery.css('float') I am getting the right value back, so it's exists for sure!
do you have any solution or smart way to do it?
Two things to consider: window.getComputedStyle() does not work in IE < 9 (docs here). Also, when accessing the float value via element.style, the property is named cssFloat because 'float' is a reserved word in JS (docs here). In IE < 9, the property is named styleFloat.
The reason your example works via jQuery is because jQuery knows of the inherent browser differences when reading calculated styles, and smoothes over them so that you can access them via a consistent API.
element.style maps to the style attribute, which does not consider inherited/external styles. For old IE, the property you want is element.currentStyle, which takes the inherited styles into account.
If you need a solution that does not rely on jQuery, you'll need to check for window.getComputedStyle() and use it if present, and fall-back to element.currentStyle for old IE (using the property styleFloat).
Hope that helps, cheers!

Can I access a non-existent or non-valid css property with jQuery?

There are 2 parts to this question:
If I define a CSS transition and try to access it with jQuery's .css() method, can I reliably assume that if the browser I'm running on does not support that CSS property it will always return undefined?
If I DON'T define a CSS property and try to access it with jQuery's .css() method, can I reliably assume that it will always return undefined?
The short answer is, #1. yes. #2. No.
The long answer is: #1. yes, you can make up a classname to test this, for example:
browser-foo: blue;
http://jsfiddle.net/32dzN/1/
If you haven't already, check out Modernizr. They provide excellent feature detection, I believe they put it into a DOM element off the screen if I recall correctly.
As for #2, that's not how it works at all. Because there are computed styles, as well as defined styles. For example, if you try to get the opacity of an element that you haven't set opacity on, it will return as 1.

style.setProperty does not render

It seems like using this function would be more portable or reliable, because the alternative is to set an attribute:
element.style.setProperty(styleproperty, valuestring);
element.setAttribute('style',styleproperty+': '+valuestring+';');
The second method would also seem slightly more inefficient though that's hardly a concern.
But at least on Chrome, the style does not update on the page unless I use the setAttribute method.
The reason why this is a bit of an issue, is that I have potentially many different separate style properties I want to modify independently of the others. I have to do a whole lot of string parsing and processing if I can't make use of setProperty, removeProperty, etc. I have to pull out the style string, search it, modify it, and set it back in via setAttribute. Should work, but I don't like it.
Is there a reason for this? Is this a bug? My guess is that setAttribute triggers something for the browser to perform a re-render. What is a suitable way to force this update that is generally browser-friendly?
Setting the style attribute directly has consequences that may be undesirable: it will wipe out all existing styles set in the element's style attribute, and setAttribute is broken in older IE (and compatibility modes in later IE). Much safer is to use the element's style property directly to set only the style property you need:
element.style[styleproperty] = valuestring;
This will update the page immediately in all major browsers.
One caveat: CSS style properties (generally using dashes, such as in background-color) do not map precisely to properties of the DOM element's style object (generally camel case, such as in backgroundColor). There are also exceptions to this rule.

Javascript/Jquery: .css pixel-values

I just realised there is a difference between
<foo>.css('marginTop')
(which I thought is the standard jquery-notation) and
<foo>.css('margin-top')
(which I thought was non-standard).
If has margin-top: 3em; (for example), the first notation gives me 3em, the second notation gives me 48px (which is 3em in Pixels).
I like this behaviour but I could not find anything about it in the API (or am I blind?)
Why is this the case and where can I find information about it?
P.S.: Just to be precise: of course other attributes but margin-top work aswell...
Thank you!
The doc says “jQuery can equally interpret the CSS and DOM formatting of multiple-word properties”, but in reality it is doing that through rough and ready hacks which don't always behave predictably.
In particular, if you supply a DOM-style camelCaseName, it will first try to access the inline style declaration as style.camelCaseName. Then if that fails (typically because the style was not set inline), it falls back to trying getComputedStyle with the camelCaseName converted to hyphen-separated-name(*). The computed style is not the same thing as the declared style: the browser can resolve various relative declarations in a computed style, such as converting lengths to pixel units.
However, the reverse does not hold! If you supply a CSS-style hyphen-separated-name, it jumps straight to the computed style(*) code without trying to convert to camelCaseName and look at the inline style.
I don't think I'd want to rely on this behaviour... it smells a little bit buggy to me. If you can keep the inline style declaration off the element you want to measure, you should be able to ensure you always get the computed style back regardless of which name type you use. But then again, jQuery doesn't give you that as a documented promise. Such is the nature of trying to hide a complicated model behind a seemingly-simple “Do What I Mean” interface.
(*): except in IE where there is no getComputedStyle function, so it falls back to a weird and fragile mix of currentStyle, runtimeStyle and document alteration to try to get a computed style out.
The difference is related to CSS and JavaScript notation of the same thing. It would not be in the jQuery API but in a CSS reference.
CSS uses the margin-top while JavaScript uses the marginTop for the same thing. The default value in CSS (margin-top) is 0px. Therefore you get the 48px instead of the 3em.
See http://www.w3schools.com/css/css_reference.asp for more info.

When does reflow happen in a DOM environment?

What kinds of activities will trigger reflow of web page with DOM?
It seems there are different points of view. According to http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/, it happens
When you add or remove a DOM node.
When you apply a style dynamically (such as element.style.width="10px").
When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE).
However, according to http://dev.opera.com/articles/view/efficient-javascript/?page=3, taking measurement triggers reflow only when there is already reflow action queued.
Does anybody have any more ideas?
Both articles are correct.
One can safely assume that whenever you're doing something that could reasonably require the dimensions of elements in the DOM be calculated that you will trigger reflow.
In addition, as far as I can tell, both articles say the same thing.
The first article says reflow happens when:
When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE), while DOM changes are queued up to be made.
The second article states:
As stated earlier, the browser may cache several changes for you, and reflow only once when those changes have all been made. However, note that taking measurements of the element will force it to reflow, so that the measurements will be correct. The changes may or may not not be visibly repainted, but the reflow itself still has to happen behind the scenes.
This effect is created when measurements are taken using properties like offsetWidth, or using methods like getComputedStyle. Even if the numbers are not used, simply using either of these while the browser is still caching changes, will be enough to trigger the hidden reflow. If these measurements are taken repeatedly, you should consider taking them just once, and storing the result, which can then be used later.
I take this to mean the same thing they said earlier. Opera will try its hardest to cache values and avoid reflow for you, but you shouldn't rely on its ability to do so.
For all intents and purposes just believe what they both say when they say that all three types of interactions can cause reflow.
Cheers.
Look at the "Rendering triggered by Property Read Access" section of Understanding Internet Explorer Rendering Behaviour, where the following code in IE will cause rendering activity.
function askforHeight () {
$("#lower").height();
}
document.body.style.display = 'none';
document.body.style.display = 'block';
This often solves those incomprehensible layout bugs.

Categories

Resources