Adding feed to digg

9d3405a5e1ea4dd08e00744a577ec50c

Why width: 100% doesn’t do what you think it does

Something I run across every so often when fixing bugs is a problem of content overflowing its parent element. The child has padding, margins, or a border, and a width set to 100%. This seems like it should fill the available space, but it protrudes out instead.

The weird behavior comes from the standard box model. According to the standard box model, when you set the width, it sets the width of the content area. The padding, border, and margin get wrapped around it. Meaning that the box, which is already the full width of it’s parent, gets pushed out beyond the edge.

The fix is painfully simple. Simply set width of the chid element to auto, or remove it entirely. Block level elements automatically fill the available space, and that calculation takes into account the borders, margin, and padding.

What’s a  ?

The non-breaking space ( ) is the workhorse of the web. It can be used in so many contexts from its use as a poor-mans indent or even to workaround bugs in IE6 and Firefox.

Not many people know the true value of a non-breaking space. As its name implies, its primary purpose to prevent line breaks. Essentially the opposite of a break tag.

A few examples

Prevent widows:

By replacing the last space in a paragraph you can prevent a widowed word.

In aliquet leo aliquet enim tincidunt non tristique tortor
feugiat. Donec gravida egestas risus quis eleifend. Donec
adipiscing dolor nec augue dignissim pharetra.

Ensure words always appear together

In aliquet leo aliquet enim tincidunt non tristique tortor
feugiat. ACME Widget XL donec gravida egestas
risus quis eleifend. Donec adipiscing dolor nec augue
dignissim pharetra.

Stacking the Deck

Managing styles can be frustrating. Most people just stuff everything into one stylesheet. This works for smaller sites really well, but it doesn’t scale to larger sites. The stylesheet gets so large that it’s difficult to know what is going to override what. You end up relying in tools like Firebug to find out how adding a new style is going to affect the site.

She’s a brick house

You can’t really get rid of that global stylesheet because defining styles that apply to the whole site incredibly useful. You don’t want have the same styles duplicated across multiple stylesheets. That causes bloat. It makes updating the styles difficult too, but it would be great to have page level granularity. So when the creative department comes down on you like a ton of bricks, you can change the blue to gold in a flash. (actually it was more of a amber-canary with a splash of wheat).

The trick is to do both. Start with a global stylesheet and define the most commonly used styles. Use good defaults: define all your font families and sizes; create classes for all of your sprites; and create all of the utility classes for floating and clearing elements. This will be the foundation for all of your future work.

Then create a set mid-level of stylesheets. You would include this one immediately after your global sheet. One for each section of your site. These stylesheets will be your work horses. This is where you setup your layout fundamentals for section.

And finally

On the pages that need it. Create page specific stylesheets. Included after your section stylesheet. So, now, when the client says that they actually liked the blue better. It’s now a 5 second change.

Why plain, vanilla, anchors are a bad idea.

A few days ago I was testing a soon to be released site. I followed a link I had never seen before and suddenly found my self confused and disoriented. In retrospect it could’ve been the fact I had just ran into a glass door on my way in (I totally didn’t see it there).

But, never the less, it lead me to tweet this:

GUIDELINE: Users should never “teleport” between areas of the page. This can be disorienting. Show the movement from one place to the other.

Ice, Ice, Baby

The reason why I suggested that is not because of the severe “bling” deficiency on the internet. Which, I might add, is getting worse by the day. Its, also, definitely not because I just got laid off and really need a job (see my resume). Its because its just plain bad UI design.

Now, don’t get me wrong. There are a lot of reasons you want link to a specific part of a document, but the way browsers implement this functionality is bad. Fortunately this is an easy fix if you use the scrollTo jQuery plugin

$(function() {
	$("a[href^='#']").click(function (e) {
		var element = this.hash;
		e.preventDefault();
		$.scrollTo(element, 1000, {
			offset: -50,
			onAfter: function() {
				$(element).css({"background": "red"});
			}
		});
	})
});

Scientific Notation – Quick JS Snippy

Number.prototype.toScientific = function (x) {
 
	var parts = this.toExponential(x).split( /[e]\+?/i ,2);
 
	return parts[0] + ((parts[1] != 0 && parts [1] != 1)? " &times; 10<sup>" + parts[1] + "</sup>": "");
}

Barbeque: A brainstorm on better Data interfaces

So, with the release of PHP 5.3 some of the new features got me thinking about better ways to query and interact with data. I’m tentatively calling it bbQuery, or bbQ for short.

Data Driven Apps

Web applications are typically driven by data and interactions between it. A typical situation involves: Querying data from the database, formatting as HTML, outputting. A few years ago it was just that simple. Today you have JSON, RSS, and other various formats.

Going by the standard model, you have to create each page separately for all of the various formats, duplicating code. I can’t say I solved this problem entirely, but I’m getting close.

Grab the Steaks, It’s Time for a bbQ

The goal is to be functionally similar to SQL but include a formatting layer that intelligently determines the way to display the data. The following snippet show how the old model can be transitioned to bbQ.

$DB('Children')
   ->select('children_id', 'dob', 'fitness', 'status')
   ->format(function ($row) {
      echo "${row['dob']} - ${row['fitness']} - ${row['status']}";
   });

A simple example using the gFonted database. The first line selects the table from the database. On the second we select the columns we want in the query. The query results are then returned in to a callback from the format function. Very quickly you could create predefined formatting functions.

$DB('Children')
   ->select('*')
   ->left_join('Template', 'children_id')
   ->format(bbQuery::format_table); // predefined format functions

But thats far from automatic, intelligent maybe. Its impossible to guess what format anyone will need. There are a few generic formats (JSON and XML) that could be dealt with automatically.

$DB('Children')
   ->select('*')
   ->left_join('Template', 'children_id')
   ->limit(5)
   ->order_by('fitness', bbQuery::asc) // bbQuery::asc == "asc"
   ->set_type("application/json")
   ->format();
 
$DB('Children')
   ->select('*')
   ->left_join('Template', 'children_id')
   ->limit(5) // is a variable that gets overwritten
   ->order_by('fitness', bbQuery::desc) // order by's are string
   ->order_by('dob', bbQuery::asc) // and gets appended to
   ->set_type("application/xml")
   ->format();

Going the Other Direction

Sometimes its useful to put data into a database. I guess thats an understatement. Its also an understatement to say that doing so is a simple task. An example of standard data insertion:

$DB('Correct')
   ->insert_into('children_id', 'correct')  // returns an insert object
   ->values(12, false);

However this could be greatly simplified. MySQL already knows the datatype for the column, so validation could be automated. The data could even be automatically inserted from a form.

<form>
   <input name="children_id" type="text" value="12" />
   <input name="correct" type="checkbox" />
</form>
 
<?
$DB['Children']
   ->insert_into('children_id',  'correct')  // returns an insert object
   ->from_form();
?>

And finally some other useful snippets:

$DB->query("select * from Children")
    ->format(bbQuery::format_table);
 
$DB('test')
   ->create_table() // returns a create_table object
   ->column('test_id', bbQuery::id_column()) // id is special if set as a primary key, unsigned integer autoincrement
   ->column('test_foreign_id', bbQuery::id_column()) // just a unsigned integer
   ->column('test_char', bbQuery::char_column(10)) // field length as parameter
   ->column('test_int', bbQuery::integer_column(bbQuery::big), 0) // default as third parameter to column
   ->column('test_enum', bbQuery::enum_column('val', 'val3', 'val2')) // enum is varidaic
   ->primary_key('test_id')
   ->foreign_key('test_foreign_id', 'Correct');
 
$DB('test')
   ->alter_table() // returns a alter_table object
   ->add('test_timestamp', bbQuery::timestamp_column, bbQuery::now)
   ->drop('test_int');
 
$DB->query("truncate table test"); // format is not appropriate here

Cosmic Sans source available at GitHub

Cosmic Sans, a font showing the planets to scale, is now available at GitHub.

If you are an artist, astronimer, or a space enthusiast you can help contribute.  A list of desired space objects are at Google Docs.  If your interested leave a comment, or just fork the get repository and send me a Pull Request.

Dr. JavaScript and Mr. PHP

In my last post I wrote about JavaScript variables.  It stemmed from realizing that the dollar sign ($) was a valid character in JavaScript.  I struggled to find any use for all of these new characters – other than making code unreadable.  One thing stuck out in my mind.  An old episode of Hak .5 where Billy Hoffman described a worm that would be written in a hybrid of Perl and JavaScript.  A Dr. Jekyll and Mr. Hyde scenario where the worm would embed itself in a web page and search for a “host”, and then infect that host.  That host would then serve pages with the worm embedded in it, creating exponential growth.  Unfortunately at the time he didn’t have a proof of concept.

Hybrid Means Better Gas Mileage

Unlike Billy’s technique I chose to use PHP instead of Perl.  Many of the language constructs are identical between PHP and JavaScript.  However there are few snags.

  • PHP scripts have to start and end with ‘<?’ and ‘?>’ respectively.
  • PHP variables must start with a ‘$’.
  • Most of JavaScript’s standard functions are wrapped in objects.  Math, String, etc.
  • PHP uses the ‘.’ for concatenation, while JavaScript uses ‘+’.
  • PHP uses C++ style definition for objects, while JavaScript uses a prototype definition.
  • JavaScript uses the C++ style const keyword to define constants, while PHP uses the define() function.

The Lucky Ones

Not all of these problems can be worked around, but enough of them can be worked around that functioning code can be written.

PHP scripts have to start and end with ‘<?’ and ‘?>’ respectively.
The workaround for this is to run the script using the eval() function.  The PHP’s eval() function doesn’t require the opening and closing tags as feature.
PHP variables must start with a ‘$’.
The dollar sign is a valid character in JavaScript variables, so starting them with the dollar sign poses no problem.
Most of JavaScript’s standard functions are wrapped in objects.  Math, String, etc.
PHP.js can be used to wrap the standard JavaScript functions.  Acting as a compatibility layer.
JavaScript uses the C++ style const keyword to define constants, while PHP uses the define() function.
PHP version 5.3.0 allows for the const keyword.

Taking the Plunge

As a proof of concept I wrote a small function to calculate  the great circle distance.  It computes the distance in both PHP and JavaScript.  You can find it here and hybrid PHP / JavaScript code here.

The many lives of JavaScript variables

So, It was about three months ago when I first met jQuery.  It’s a neat little library that helps JavaScript programmers easily do relatively complex things.  Among many of its features one stood out to me.  The $() function is an interesting beast that takes a CSS selector or XPath and returns a set of matching nodes.  However, the application of it was not what attracted me to it.

The Revelation

The name, a single dollar sign, is what struck me.  I never knew that such a character could be used in a variable name.  As I, and many others, were taught the only character allowed were:

  1. letters
  2. underscores
  3. and numbers so long they are not the first character

I was interested and decided to embark on quest to figure out what characters were allowed and which weren’t.  This took me to the ECMA-262 specification, the standard for JavaScript, or ECMA Script as its formally called. The standard states:

Identifiers are interpreted according to the grammar given in Section 5.16 of the upcoming version 3.0 of the Unicode standard, with some small modifications.

The Unicode Standard allows for nearly 14,000 characters to be used in variables, as opposed to the measly 63 that are commonly used.

The Disappointment

I instantly tried to stuff Sigmas (Σ) and Double Struck N’s (ℕ) in to my code, but to my dismay, they didn’t work.  Disappointing? Yes.  Surprising? No.  It seems to be this way with all web standard’s, either implemented wrongly or incompletely (or both, heres looking at you Microsoft).  So, to test compliance I wrote a small JavaScript that creates a variable, using one of the Unicode characters, and assigns a value to it.  If throws an exception, then that means the browser doesn’t support that character.  Simple enough, but who wins this browser compliance battle.  So far Opera, it supports 99.5% of all characters.  Heres the data I’ve collected so far:

Browser Chars Tested Non Supported Chars % Not Supported
Opera 9.27
(Ubuntu Linux)
13935 78 0.5597416576964478
Opera 9.63
(Windows XP & Ubuntu Linux)
13935 80 0.5740940078937926
Internet Explorer 8
(Windows 7 and XP)
13935 2131 15.292429135270902
Google Chrome
(Windows XP)
13935 2746 19.705776820954434
Internet Explorer 7 & 6
(Windows XP)
13935 4340 31.144599928238246
Firefox 3.0, 3.5, 3.6
(Windows XP & Ubuntu Linux)
13935 7220 51.811984212414785

Yeah, I know thats a pathetically small dataset, but you can help run the test script and then post the last three lines in the comments along with the browser, version, and OS.  WARNING: This script takes a very long time to execute, it may appear to lock your browser up, but be patient.

On an unrelated note, Chrome’s Javascript engine was suprisingly fast.