17
Jul/09
0

$(document).ready() Shortcut

When writing jquery you almost always put your code within a ready block:

$(document).ready(function(){
    // Code...
});

And I always forget the exact syntax. I just found that jQuery has a shortcut:

$(function(){
    // Code...
});

Much better!

12
May/09
1

CSS Element Sizing

While working on our new UI at $work we ran in to issues using the YUI layout manager as its very quirky and hard to customize. So, I ended up writing an entirely new layout manager. As part of this I found that the way I thought elements resized was nothing like reality. I’m a big jQuery fan so this diagram below refers to jQuery methods, but the concept applies to CSS in general.

css_element_sizing

As you can see the height of an element represent only the internal height of the element, not taking in to account the margin, border, or padding. This I already knew, but I didn’t know how the corresponding jQuery methods fit in here. jQuery.height() has the same value as the CSS height attribute. jQuery.innerHeight is the CSS height plus the CSS top and bottom padding. jQuery.outerHeight() includes the CSS height, the top and bottom padding, and the top and bottom border. And, finally, jQuery.outerHeight(true) works the same as jQuery.outerHeight(), but also includes the top and bottom margin.

12
May/09
1

Setting an Element’s Outer Size

When setting an element’s width or height you are setting the inner-most width and height, without taking in to account the padding, border, or margin. When writing application-like web sites this is not the behavior you want – usually you want exact control of the entire width and height of the element. Here’s a very simple jQuery plugin that I wrote to make this very easy to do.

jQuery.fn.setOuterWidth = function( newWidth ) {
    var difference = this.outerWidth(true) - this.width();
    return this.width( newWidth - difference );
};

jQuery.fn.setOuterHeight = function( newHeight ) {
    var difference = this.outerHeight(true) - this.height();
    return this.height( newHeight - difference );
};

Then all you have to do is use obj.setOuterWidth(…) instead of obj.width(…) to resize the entire element.