I'm working on a jQuery function to set the height of a div based on the height of the window and some other elements, and I noticed something strange. The outerHeight() function seems to accept an integer parameter, even though the documentation doesn't specify that one is allowed.
So this seems to work in both Chrome and Firefox:
var o_height = $("#content").outerHeight();
var n_height = $(window).outerHeight() - $("#nav").outerHeight();
if (n_height > o_height) {
$("#content").outerHeight(n_height);
}
The alternative is to calculate the padding and then subtract it, which is a few lines longer:
var o_height = $("#content").outerHeight();
var n_height = $(window).outerHeight() - $("#nav").outerHeight();
if (n_height > o_height) {
var padding = $("#content").outerHeight() - $("#content").height();
$("#content").height(n_height - padding);
}
What I'm wondering is whether it's safe to use the shorter version. I'll be doing stuff like this several times, so I'd rather cut down on the length of the script, but not at the cost of stability. Is this a stable, but undocumented feature, or do I just need to accept the extra weight in the function?
In case anybody else stumbles upon this, it appears that this functionality was actually added all the way back in 1.8.0 for both outerHeight and outerWidth, but that despite frequent reports, the documentation still hasn't been updated.
Related
In jQuery, I can very easily get the current computed height for an element that includes padding, border, and optionally margin by using outerHeight()...
// returns height of element + border + padding + margin
$('.my-element').outerHeight(true);
How would I do this in YUI? I'm currently using version 2.8.1.
Similar to this question, I can always do getComputedStyle() for height, border, padding, and margin, but that is a lot of manual labor which includes parsing the return values and grabbing the correct values that are needed and doing the math myself.
Isn't there some equivalent function to jQuery's outerHeight() in YUI that does all of this for me?
Solution
I ended up writing my own solution since I couldn't find a jQuery outerheight() equivalent. I've posted the solution as an answer here.
There is no built-in way of getting the outer width of an element with its margin in YUI. Like #jshirley mentions, there is offsetWidth, but it doesn't take margins into account. You can however create a function that adds the margin very easily:
Y.Node.ATTRS.outerHeight = {
getter: function () {
return this.get('offsetHeight') +
parseFloat(this.getComputedStyle('marginTop')) +
parseFloat(this.getComputedStyle('marginBottom'));
}
};
Y.Node.ATTRS.outerWidth = {
getter: function () {
return this.get('offsetWidth') +
parseFloat(this.getComputedStyle('marginLeft')) +
parseFloat(this.getComputedStyle('marginRight'));
}
};
Then you can get the outer width by doing Y.one(selector).get('outerWidth'). Here's an example based on #jshirley's code: http://jsbin.com/aretab/4/.
Just keep in mind that dimensions are usually a source of bugs in browsers and this doesn't take into account some stuff (ie: dimensions of the document) jQuery tries to catch (see https://github.com/jquery/jquery/blob/master/src/dimensions.js).
If you wanted to avoid the manual labor, wrap the element in a div and get the computed style of that.
If it's something you're doing more than once, create a function/plugin to reuse.
According to http://www.jsrosettastone.com/, you should be using .get('offsetHeight').
This example shows the equivalency: http://jsbin.com/aretab/1/edit
I ended up writing my own little utility function for this:
/**
* Calculates the outer height for the given DOM element, including the
* contributions of padding, border, and margin.
*
* #param el - the element of which to calculate the outer height
*/
function calculateElementOuterHeight(el) {
var height = 0;
var attributeHeight = 0;
var attributes = [
'height',
'border-top-width',
'border-bottom-width',
'padding-top',
'padding-bottom',
'margin-top',
'margin-bottom'
];
for (var i = 0; i < attributes.length; i++) {
// for most browsers, getStyle() will get us a value for the attribute
// that is parse-able into a number
attributeHeight = parseInt(YAHOO.util.Dom.getStyle(el, attributes[i]), 10);
// if the browser returns something that is not parse-able, like "auto",
// try getComputedStyle(); should get us what we need
if (isNaN(attributeHeight)) {
attributeHeight = parseInt(YAHOO.util.Dom.getComputedStyle(el, attributes[i]), 10);
}
// if we have an actual numeric value now, add it to the height,
// otherwise ignore it
if (!isNaN(attributeHeight)) {
height += attributeHeight;
}
}
return isNaN(height) ? 0 : height;
}
This seems to work across all modern browsers. I've tested it in Chrome, Firefox (idk about 3.6, but the latest version works), Safari, Opera, & IE 7,8,9. Let me know what you guys think!
I have several fixed position divs with the same class at varying distances from the left edge of the window, and I'd like to increase/decrease that distance by an equal amount on each div when a certain action happens (in this case, the window being resized). I've tried positioning them with CSS and percentages rather than pixels, but it doesn't quite do the job.
Is there a way to store the position of each of those divs in an array and then add/subtract a given amount of pixels?
Here's what I've tried so far - I'm still getting my head around JS so this could be really bad for all I know, but here goes:
roomObjects = $('.object-pos');
var objectCount = 0;
for ( var objectCount = 0; objectCount < 10; objectCount++;) {
roomObjects = rooomObjects[objectCount];
console.log(roomObjects.css("background-position").split(" "));
}
Do you mind sharing why percentages wouldn't work? Usually that's what I would recommend if you're wanting the page to scale correctly on window resizes. I guess if you really wanted to you could do something like:
$(window).resize(function() {
$('#whateverdiv').style.whateverproperty = $('#whateverdiv').style.whateverproperty.toString() + (newPosition - oldPosition);
oldPosition = newPosition;
}
this is obviously not the complete code, but you should be able to fill in the blanks. You'll have to set the oldPosition variable on page load with the original position so that the function works the first time.
edit: you'll also have to strip off the units from the x.style.property string, so that you'll be able to add the value to it
A problem you might well be facing is that when retrieving the current left or top properties, they are returned as a string, with px of % on the end. Try running a parseInt() on the returned values to get a number, then you might well be able to add to the values. Just be sure, when reassigning, that you concatenate "px" or "%" on the end as appropriate.
You could use a bit of jQuery :
var el = $("#id");
var top = el.css("top");
el.css("top", top * 1.2); // increase top by 20%
saves mucking around in the DOM
This might be useful if you want to position things relatively: http://docs.jquery.com/UI/Position
I'm getting a weird error where in Internet Explorer 7, when I call Math.round on a float it gives me an "Invalid Argument" error. Consider the following:
var elementLeft = parseInt(element.style.left); // Here we're actually getting NaN
function Foo(x) {
this.x = x;
this.apply = function(element) {
element.style.left = Math.round(this.x) + 'px';
};
}
Foo(elementLeft);
In this case x is a non-negative number and element is just a DOM element in my page (a div, in fact).
Any ideas?
EDIT: The variable passed in as the x parameter is actually initialized earlier as parseInt(element.style.left). It appears that the first time I try to read element.style.left, IE is actually giving back NaN. I have updated the code to reflect this. Anyone know any workarounds for this?
It appears that the first time I try to read element.style.left, IE is actually giving back NaN.
The first time you read element.style.left, is there actually any left style set on the element? Remember element.style only reflects style properties set in the inline style="..." attribute and not those applied by stylesheets.
If you haven't set an inline style, style.left will give you the undefined object, which does indeed parseInt to NaN.
Is IE defaulting x to a bad value?
Scroll down to Item 10 on this page:
Everything was working fine in
Firefox, Google Chrome etal. But I was
having problems with IE (of all
flavours). No selection tool would be
presented and a javascript warning was
produced which told me about an
'Invalid argument' being submitted to
the Math.round function.
The cause was that when you first
click on the image to start your
selection, the scaleX and scaleY
variables in the javascript on the
page result in a value of Infinity.
Firefox and every other browser seems
to silently step over this and carry
on processing as normal. IE of course
did not.
The solution was to add the following
line after the initial scaleX and
scaleY variables are calculated. This
appears to have solved the problem
fully. if(scaleX == Infinity || scaleY
== Infinity) return false; I hope this helps someone else and saves them the
hour of hunting it cost me ;o)
I don't think it's Math.round() that's giving you the error. It's probably the CSS subsystem. Try an alert() on the value that you're getting.
Some frameworks such as jQuery have facilities to read the calculated position of elements -- without requiring you to have explicitly set CSS position properties on them. Try reading the position of your element through jQuery. It might work.
For some reasons Javascript only works for the inline styling.
For example
<div style="left:500px;"></div>
if you wish to work on the position of an element, try setting the initial position in Java Script file, example:
function Xyz() {
var elem = document.getElementById('id');
elem.style.left = 500px;
numberLeft = 500;
//Now you can manipulate the position
var increment= 50;
var newLeft = numberLeft + increment;
elem.style.left = newLeft + 'px';
}
You get the idea. Put your logic in.
The while statement in this function runs too slow (prevents page load for 4-5 seconds) in IE/firefox, but fast in safari...
It's measuring pixel width of text on a page and truncating until text reaches ideal width:
function constrain(text, ideal_width){
$('.temp_item').html(text);
var item_width = $('span.temp_item').width();
var ideal = parseInt(ideal_width);
var smaller_text = text;
var original = text.length;
while (item_width > ideal) {
smaller_text = smaller_text.substr(0, (smaller_text.length-1));
$('.temp_item').html(smaller_text);
item_width = $('span.temp_item').width();
}
var final_length = smaller_text.length;
if (final_length != original) {
return (smaller_text + '…');
} else {
return text;
}
}
Any way to improve performance? How would I convert this to a bubble-sort function?
Thanks!
move the calls to $() outside of the loop, and store its result in a temporary variable. Running that function is going to be the slowest thing in your code, aside from the call to .html().
They work very very hard on making the selector engines in libraries fast, but it's still dog slow compared to normal javascript operations (like looking up a variable in the local scope) because it has to interact with the dom. Especially if you're using a class selector like that, jquery has to loop through basically every element in the document looking at each class attribute and running a regex on it. Every go round the loop! Get as much of that stuff out of your tight loops as you can. Webkit runs it fast because it has .getElementsByClassName while the other browsers don't. (yet).
Instead of removing one character at time until you find the ideal width, you could use a binary search.
I see that the problem is that you are constantly modifying the DOM in the loop, by setting the html of the temp_item, and then re reading the width.
I don't know the context of your problem, but trying to adjust the layout by measuring the rendered elements is not a good practice from my point of view.
Maybe you could approach the problem from a different angle. Truncating to a fixed width is common.
Other possibility (hack?) if dont have choices, could be to use the overflow css property of the container element and put the … in other element next to the text. Though i recommend you to rethink the need of solving the problem the way you are intending.
Hugo
Other than the suggestion by Breton, another possibility to speed up your algorithm would be to use a binary search on the text length. Currently you are decrementing the length by one character at a time - this is O(N) in the length of the string. Instead, use a search which will be O(log(N)).
Roughly speaking, something like this:
function constrain(text, ideal_width){
...
var temp_item = $('.temp_item');
var span_temp_item = $('span.temp_item');
var text_len_lower = 0;
var text_len_higher = smaller_text.length;
while (true) {
if (item_width > ideal)
{
// make smaller to the mean of "lower" and this
text_len_higher = smaller_text.length;
smaller_text = text.substr(0,
((smaller_text.length + text_len_lower)/2));
}
else
{
if (smaller_text.length>=text_len_higher) break;
// make larger to the mean of "higher" and this
text_len_lower = smaller_text.length;
smaller_text = text.substr(0,
((smaller_text.length + text_len_higher)/2));
}
temp_item.html(smaller_text);
item_width = span_temp_item.width();
}
...
}
One thing to note is that each time you add something to the DOM, or change the html in a node, the page has to redraw itself, which is an expensive operation. Moving any HTML updates outside of a loop might help speed things up quite a bit.
As other have mentioned, you could move the calls to $() to outside the loop. You can create a reference to the element, then just call the methods on it within the loop as 1800 INFORMATION mentioned.
If you use Firefox with the Firebug plugin, there's a great way of profiling the code to see what's taking the longest time. Just click profile under the first tab, do your action, then click profile again. It'll show a table with the time it took for each part of your code. Chances are you'll see a lot of things in the list that are in your js framework library; but you can isolate that as well with a little trial and error.
I have some legacy javascript that freezes the tfoot/thead of a table and lets the body scroll, it works fine except in IE8 its very slow.
I traced the problem to reading the clientWidth property of a cell in the tfoot/thead... in ie6/7 and FireFox 1.5-3 it takes around 3ms to read the clientWidth property... in IE8 it takes over 200ms and longer when the number of cells in the table is increased.
Is this a known bug ? is there any work around or solution ?
I've solved this problem if you are still interested. The solution is quite complex. Basically, you need to attach a simple HTC to the element and cache its clientWidth/Height.
The simple HTC looks like this:
<component lightweight="true">
<script>
window.clientWidth2[uniqueID]=clientWidth;
window.clientHeight2[uniqueID]=clientHeight;
</script>
</component>
You need to attach the HTC using CSS:
.my-table td {behavior: url(simple.htc);}
Remember that you only need to attach the behavior for IE8!
You then use some JavaScript to create getters for the cached values:
var WIDTH = "clientWidth",
HEIGHT = "clientHeight";
if (8 == document.documentMode) {
window.clientWidth2 = {};
Object.defineProperty(Element.prototype, "clientWidth2", {
get: function() {
return window.clientWidth2[this.uniqueID] || this.clientWidth;
}
});
window.clientHeight2 = {};
Object.defineProperty(Element.prototype, "clientHeight2", {
get: function() {
return window.clientHeight2[this.uniqueID] || this.clientHeight;
}
});
WIDTH = "clientWidth2";
HEIGHT = "clientHeight2";
}
Notice that I created the constants WIDTH/HEIGHT. You should use these to get the width/height of your elements:
var width = element[WIDTH];
It's complicated but it works. I had the same problem as you, accessing clientWidth was incredibly slow. This solves the problem very well. It is still not as fast IE7 but it is back to being usable again.
I was unable to find any documentation that this is a known bug. To improve performance, why not cache the clientWidth property and update the cache periodically? I.E if you code was:
var someValue = someElement.clientWidth + somethingElse;
Change that to:
// Note the following 3 lines use prototype
// To do this without prototype, create the function,
// create a closure out of it, and have the function
// repeatedly call itself using setTimeout() with a timeout of 1000
// milliseconds (or more/less depending on performance you need)
var updateCache = function() {
this. clientWidthCache = $('someElement').clientWidth;
};
new PeriodicalExecuter(updateCache.bind(this),1);
var someValue = this.clientWidthCache + somethingElse
Your problem may be related to something else (and not only the clientwidth call): are your updating/resizing anyhting in your DOM while calling this function?
Your browser could be busy doing reflow on IE8, thus making clientwidth slower?
IE 8 has the ability to switch between IE versions and also there is a compatibility mode.
Have you tried switching to Compatibility Mode? Does that make any difference?
I though I had noticed a slow performance also when reading the width properties. And there may very well be.
However, I discovered that the main impact to performance in our app was that the function which was attached to the window's on resize event was itself somehow causing another resize which caused a cascading effect, though not an infinite loop. I realized this when i saw the call count for the function was orders of magnitude larger in IE8 than in IE7 (love the IE Developer Tool). I think the reason is that some activities on elements, like setting element widths perhaps, now cause a reflow in IE8 that did not do so in IE7.
I fixed it by setting the window's resize event to: resize="return myfunction();" instead of just resize="myfunction();" and making sure myfunction returned false;
I realize the original question is several months old but I figured I'd post my findings in case someone else can benefit.