Omnibus

You just got a 2% pay increase! Use it wisely.

Some things age more gracefully than others. This was first posted 8 years ago, so caveat lector. Links may be broken, things may be wrong (this is the internet, after all), and you may be better off finding more recent and relevant content. Blogs are rarely graceful on a good day, let alone after a few years.

…well, kind of, sort of. On Dec. 17, Congress agreed to extend many of the Bush-era tax cuts, which is generally pretty awesome in the more-money-in-my-pocket way but not so much in the holy-staggering-national-debt-increase-Batman! way. In addition to the extensions is what I’ll call Making Work Pay 2.0 (officially the Tax Relief Act)—a employee payroll tax decrease.

The payroll tax, more commonly known as the Social Security tax, is normally 6.2% of your gross income. Everyone who earns money by legal, non-tax-avoiding ways pays this, no ifs-ands-or-buts, although if you make more than $106,800, your maximum tax is $6,621. For 2011, the tax for employees is reduced to 4.2% (a max savings of $2,136). If you’re self-employed, you’ll still have to pay the full employer-side 6.2% for a total of 10.4% instead of 12.4%. And if you’re an employer, you still have to pay 6.2% for each of your employees.

So, that begs the question: what are you going to do with it?

I’ve already made my decision—it’s going straight into my retirement account. I figure I might as well save for my own retirement while I’m getting a reprieve from paying for someone else’s. The proper paperwork has been signed, sealed and delivered. I waffled about this or paying off debt faster, but I’ll have my over-5%-interest consumer debt all taken care of by the end of January, and I expect that my retirement returns will be higher than that in the long run. It just makes financial sense. After all, thanks to compounding interest, your early 20s is a great time to start saving for retirement.

What’s your plan, Stan?

One note of import: since it’s all very last minute, your employer has until Jan. 31 to fix their payroll system so that the money goes in your check instead of to the government. This means you may not see an increase until February. Then, your employer has until Mar. 31 to give you whatever they owe you from not having the system set up correctly in January.

IE Change Event Delay

The Web is ever changing, and this article is relatively ancient having been published 8 years ago. It is likely out of date or even blatantly incorrect in relation to modern better practices, so proceed at your own risk.

I recently developed a sign-up form for a client that includes on-page price total calculation using JavaScript (jQuery). The premise is simple: the user provides information and specify options, then clicks a radio button to choose a specific price plan. The initial total price calculation is triggered by the change() event for the radio button elements. But, the client was concerned (and with user testing, it turned out rightly so) because in IE, the price calculation didn’t happen until the user clicked somewhere else on the page. In cases where they first clicked one option, then a different one, the price would seemingly lag behind because of IE’s delayed change event firing. It was confusing to the user, but worse—confusing for me to “fix” IE’s implementation.

The awesome news is that this has been fixed in jQuery 1.4, but the concern is still valid for older versions (which my application was using) and straight-JavaScript implementations.

The problem

In Internet Explorer, the change event fires when focus leaves the form element (an event know as blur). That means that the event happens only once a user has clicked on—or used the keyboard to navigate to—another element on the page (form or other).  In cases like mine, where a user is expecting instant feedback to their click, this causes issues with user experience. Unfortunately, this isn’t exactly a “bug,” as it’s how IE handles this event in 6, 7 and 8.

In other browsers—Firefox, Webkit-based (Safari/Chrome) and Opera—the event fires off immediately, so in order to have consistent, intelligent operation, we have to hack IE’s basic behavior. The easiest solution is to bind your function to a different event, such as the click event, but that’s generally not the right solution. There is a better one.

Why using the click event is wrong

One word: accessibility. Users—whether they have a disability that restricts their use of the mouse or like to tab about the page with the keyboard for speed—don’t always use the mouse to move from form element to form element. So, if you bind your functionality to the click event, you may end up messing with a user’s workflow, which makes for unhappy visitors. In some cases, it may even make a user unable to use your application. So don’t use that as your solution.

The real solution

If IE needs a blur event to know that the change event should fire, give it one when the element is clicked. In jQuery, that looks something like:

$("#element").click(function(){
	// In IE, we need to do blur then focus to trigger a change event
	if ($.browser.msie) {
		this.blur();
		this.focus();
	}
}).change(function(){ actionIWantOnChange(); });

This code tricks IE into thinking that focus has been changed away from the element when it is clicked. But since the change event is also triggered, the actions attached to that event also happen. Keyboard navigability still works, because even though there is no click, the change event will fire when they use the keyboard to move to another field meaning the feedback is instantaneous.

Now, you can probably improve my above example by using better feature-sniffing to test for IE instead of the browser object in jQuery, but my time for creating a fix was limited—and this code gets the job done.

Shakespeare in OP

I’m not really a theatre nerd, but I am a bit of a history and language nerd even if I have very little background in either. And like any liberal arts-studied lady, I do have an appreciation for The Bard. So, I am totally in nerd lust with the University of Kansas right now*. Why? They’re putting on a production of A Midsummer Night’s Dream in the original pronunciation (or as near as we can glean it sounded based on research of dialects and rhyming schemes). This is the first production of its kind in America, and only the fourth modern one ever.

How different is it from modern pronunciation? Well, that depends on what English you speak.

Meier said audiences will hear word play and rhymes that “haven’t worked for several hundred years (love/prove, eyes/qualities, etc.) magically restored, as Bottom, Puck and company wind the language clock back to 1595.”

“The audience will hear rough and surprisingly vernacular diction, they will hear echoes of Irish, New England and Cockney that survive to this day as ‘dialect fossils.’ And they will be delighted by how very understandable the language is, despite the intervening centuries.”

The production is going on during November, so I’m sad that I can’t see it, but evidently they plan on recording it in radio-drama form that will be available online in the future. Here’s a little preview to get your blood rushing:

For the super-nerds out there (like me), Professor Meier has provided a free e-book with links to sound files that explain the pronunciation differences. And if you are in the Kansas City/Lawrence area, lucky you!

Thanks to The History Blog and Jason Kottke for the heads up.

* For those of you outside of the Kansas/Missouri area, this is just a warning that said lust could get me disowned from my family. See, despite the civil war having ended almost 150 years ago, the border war is very much alive in MO-KAN: the border war between KU and MU, that is (and K State when they’re feeling feisty). I’m pretty “meh” about it all, seeing as I went to some hoity-toity lib arts college up here in NY, but since most my family is from the Missouri side of Kansas City, I’m expected to be a die-hard Mizzou fan. But MU is going to have to step up their seduction if they want to keep me, is all I’m saying. My grandpa was a K State alum and my sister is currently an MU student—well, MU’s redheaded step-child down in Rolla, MO—so in theory I should have a deeply ingrained dislike for KU. My bad.

Saving “Special” For a Rainy Day…

…that is exactly 74ºF at noon with partial sun from 1 pm–2:05:47 pm and a temperature drop to 72º after 4:16 pm. Do you save things that are “special,” planning to use them when just the right opportunity comes along? Especially things that have “unspecial” versions that you use more often? I do. Or, did. No, still do. But, it’s one of those things that I’m working on as part of the decluttering process, because when it comes down to it, those things are both physical and mental clutter.

For many years—as long as I can remember, actually—I’ve had the hoarding-lite habit of saving certain items that I really like with the idea that they’re too good for every day use, so I keep them for a “special day,” whatever that is. Like, the beautiful correspondence paper that my host family in Japan gave me; I’ve only used it for one or two seemingly special letters. In college, I’d save the last application or two of my rare bottle of Aveeno lotion for months while I used cheaper stuff. I’d save certain blank paper stock for just the case when I needed to print on that type of fancy media. The list goes on.

I realized that my reasons for doing this often fell under the same few reasons, over and over again.

Scarcity
If I use it now, I won’t be able to get the same thing in the future. The great thing about our consumerist world is that there are billions of products. Millions of these products are almost exactly like at least one other product, except for perhaps packaging or name. Even if you’re am unable to find that exact product in the future, surely you can find a similar—and probably better—one. But what if…? No, there are no what ifs in a decluttered, happy life.

The wonderful thing about the Internet is you can find almost anything for sale. Even if you live in the middle of nowhere, as long as you can receive mail, you can buy things. So, that beautiful Japanese paper isn’t really that scarce after all.

Cost
This is expensive, and I can’t afford to buy it all the time, so I just use it for special occasions. Part of being decluttered and happy is being smart with money. You need money to buy stuff, and when you aren’t buying random stuff, you have more money to spend on other stuff. Take that Aveeno lotion that I hoarded in college. Yes, it’s more expensive than some other types, but it does work better for my skin. But so does the similar formula store brand (see Scarcity). If you can’t afford the nice version, see if the cheaper version is just as good. A lot of times it is. Then maybe you don’t need the more expensive version.

Of course, the cheaper version might not even matter, because if you’re being financially smart, maybe you can afford the expensive version all the time, or even half the time. And if you’re not hoarding it, you are using it all, meaning you’re buying that type of product less often. Unused product socked away means you’re spending more money buying stuff you don’t actually need. (Or shop smart and use coupons when all else fails.)

Sentimentality
So-and-so gave this to me, so I don’t want to use it because it reminds me of them. This is the bane of declutterers the world over. If someone gives you a gift that is a consumable product, they intend for you to use it. (And if they don’t, well, it’s probably time to explore why you allow them to give you “gifts” instead of gifts.) You’ll be reminded of them while you’re using it. You’ll be reminded of them when you think about how happy you were when you used it. You’ll be reminded of them when you buy more for yourself because you liked it. The list goes on.

When you’re hoarding things away for a rainy day, they’re taking up room both physically and mentally. Sooner or later, you end up with all these “special” things and not enough special days. Or maybe too many special days and not enough “special” things. What will you do then, huh?

So, for the optimists in the crowd: why are you saving it? Every day can be a special day.

For the pessimists: why are you saving it? There might never be a special day.

For the realists out there: why are you saving it? It’s just taking up space and isn’t really all that special anyway.

I’m making progress. For instance, Carl’s awesome cousin gave me this amazing bath salt and lotion set last Christmas. Rather than saving it for a day that was “special,” I used it almost every day until I ran out. I was happy when I used it, not regretful. Of course, the empty bottle sat around cluttering up the bathroom for a while because I kept wanting to look up how to get more. Then I took a picture of the label (digital clutter, but less than physical) and threw out the bottle. That also made me happy, because I had less clutter. Now I just need to figure out how to buy more of it (it’s a local that produces it near his cousin, I think. I’ll follow up with her when we visit for Thanksgiving).

So, my friends who share this problem, I bestow on you this task: go use something special today. Then, come tell us about how happy it makes you, and how relieved you are that it’s been put to good use, and how it decluttered your life. And work on it every day until you break the habit, just like I’m trying to do.

Elegant Code Patterns—Set and Return a Variable in One Line

I’ve been working on a Project that Never Ends™ for well… months now. Many months. The project has moved in to phase I’ve-lost-count, and the current milestone work is speed improvement. The project is a wonderful example of what goes wrong when you don’t have a detailed plan to start with, and has evolved into a terrible mess of convoluted code. The first step in any speed improvement is to reduce as much duplication as possible. One way of doing that is by caching calculations. And you can do that with a very small amount of code, using an elegant code pattern of setting and returning a variable in a single call.

The premise

When a complicated calculation is going to be used multiple times on a page, efficiency dictates saving the result (so that the calculation is only done once). So, instead of calculating the result every time you need it, why not cache the value? You can do this using a global variable and a single function. That way, any time you need the calculation, you can call the same function—including the first time—but only calculate the value once.

A case study

A function exists to get the total sales for a specific product during a given year. It does so by querying a database that has thousands of entries for each sales transaction. This time-expensive function is used multiple times on the page and is causing the page to take far too long to load.

It’s really a rather simple function:

function getSales($customer,$year) {
     $db_record = query_database("SELECT sum(sales) as total »
                FROM sales_records WHERE customer='$customer' »
                AND year='$year'");
     return $db_record->total;
}

Line breaks marked by »

While the above function glosses over the actual database calculation (that’s all pseudo code, the functions don’t really exist), you get the idea. It’s simple, but expensive when you’re querying many thousands of records each time.

By caching the result, we can reduce the page load time by quite a bit.

$CACHE = array();
function getSales($customer,$year) {
     global $CACHE;
     if (isset($CACHE[$customer][$year])) return $CACHE[$customer][$year];
     $db_record = query_database("SELECT sum(sales) as total »
                FROM sales_records WHERE customer='$customer' »
                AND year='$year'");
     return $CACHE[$customer][$year] = $db_record->total;
}

Explaining the new code, line by line

$CACHE = array();
This line of code simply creates a global variable (a variable outside the scope of our function) to use as a cache. In this case, we’re using an array.
global $CACHE;
Now that we’re in the function, we need to get access to our global variable. This line of code does just that. It declares that any time the variable $CACHE is used, it is referring to the global version.
if (isset($CACHE[$customer][$year])) return $CACHE[$customer][$year];
This is where the cache magic happens. If this is the second or later time the function has been called, the value has already been cached. We check to see if the correct cache value exists, and if it does, we return it. That exits the function immediately, meaning we return the correct value, but don’t do the expensive calculation.
$db_record = query_database…
This line is the calculation from the unoptimized function. If the result hasn’t been cached (that is, this is the first time the function has been called), we have to do the calculation. There’s no need to wrap this in an else clause, though, because when the previous if statement is true, this code is never reached.
return $CACHE[$customer][$year] = $db_record->total;

This is the magic from the title of the blog post. It sets and returns a value (the value to the right of the assignment operator [=]) at the same time. You’ve probably written something like this before:

$variable = $value;
return $variable

In PHP, however, you can do that same thing with a single line of code:

return $variable = $value

It’s elegant and simple. That’s what we’re doing in this line.

Caveat: this code pattern is wonderful for returning simple values. It doesn’t work for whole arrays. That is, you can return the value of one item in an array, as we do in the function, but you couldn’t return a whole array. That must be done with the two lines of code.

The result

I’m not going to put precise empirical evidence (execution times) on here, because your results will vary widely depending on your project and data. But, to give an idea, the project the case study is based on saw an average page load time reduction from 20s to 4s. Not a single other thing was done to the code beyond caching the values of the calculation. Your results may see less of a savings or more. In my case, we were dealing with a database containing more than 15,000 individual records that were being looked at each time the calculation query was made.

Depending on your exact project, there can be more improvements to this code. For instance, lookups in a multi-dimensional array are more expensive than ones in a one-dimensional array or an integer variable. But the concept transcends projects: cache and return the value at once, and you can save precious time by not recalculating each time the function is called.

Have you seen or used this code pattern before? Do you love it or hate it?

Elegant Code Patterns—Drop the Else When Code is Repeated

I’m working on launching a new project that has been eating up a lot of my time. Partially because any new project has a habit of eating up a lot of time, but also because I’m really focusing on using this project as a solid base for a few others, meaning I want my code to be elegant, my ideas well-executed, and my implementation in a way that means I won’t want to scrap it and start over in the future as I do far too often. Part of that employing elegant code patterns. One of my most often used patterns involves dropping the else statement when I have code repeated in different logic clauses.

The premise

One of the countless ways of using the if…else construct is to do one thing if a certain variable is one value, or do something else if it is not. A lot of times this results in duplicating code. Duplicate code is inelegant, and introduces a greater opportunity for error when, for instance, one line is changed, but its clone is not.

The solution: structure your code to reduce duplicate code.

A case study

A project is using a CMS that provides a tag to retrieve the path to a featured image for a page. If no such image exists, it returns the path for an empty filler image. There’s no way within the CMS to change what that filler image is, but this project calls for using something else as a filler.

The goal: display the proper featured image or correct placeholder using an img tag.

The process: get the image path, and check if it is the default filler image. If it is, change the path to the new filler. Display the correct image.

The inherited code looked something like this (PHP):

$image_path = get_image_path($page);
if ($image_path == "/path/to/default_filler.png") {
   echo "<img src="/path/to/desired/filler.png" alt=" " />";
} else {
   echo "<img src="$image_path" alt=" " />";
}

In this case, the logical clauses are doing the exact same thing: printing out an image tag. The only difference is the path being printed. What if you later decide to add in an alt value, or reuse this code on an HTML page instead of XHTML? You might forget to change both lines. There’s a more elegant way.

The refined code

Refining the code, we can completely drop the else statement. Instead of printing the tag in each clause, we simply change the value of $image_path to be equal to the new filler image path if it is set to the wrong one. Then, we print the image tag using the value of $image_path.

$image_path = get_image_path($page);
if ($image_path == "/path/to/default_filler.png") {
    $image_path = "/path/to/desired/filler.png";
}
echo "<img src="$image_path" alt=" " />";

Depending on your school of thought on using braces with logical constructs, you can even reduce this code to three lines. But, regardless of brace use, the refined code is a lot more elegant and maintainable than the old code.

Going further, in this case our code pattern was only being used once, but if you were also repeating this pattern, you would turn it into a function to be called each time rather than copying the code.

Any time you find yourself repeating code, especially inside of logical constructs, see if you can simplify and refine your code. It makes it easier to read, easier to update, and is often much more efficient.

Why is date() Returning 12/31/1969?

 In PHP, a good sign that something is wrong with your date data or logic is when you start seeing dates displayed as “12/31/1969” (or however you specified the format). Unfortunately, there’s not a one-fits-all solution to that, since it could be caused by any number of things, but ultimately, the root of the matter is that you’re passing an invalid timestamp into date(). So while I can’t answer what’s wrong in your specific code, I can tell you why it is happening.

All about date()

In PHP, the date function takes in a Unix timestamp, then formats it according to the format mask you provide. To display today’s date, you only need to provide a mask, no timestamp, as the timestamp argument will default to the value of time() (as in, right that moment).

In code:

<?php echo date("m/d/Y"); ?>

Which evaluated as [date format="m/d/Y"] when this page loaded.

But when you want to display a date in the past or future, you have to provide a timestamp. A Unix timestamp to be exact.

The Unix timestamp

The Unix timestamp is defined in seconds since the Unix Epoch, otherwise known as January 1, 1970 at 0:00:00 UTC.

In PHP, you can retrieve the timestamp using the time function. In code:

<?php echo time() ?>

Which evaluated as [time] when this page loaded.

In order to get a timestamp value from a time string, such as "2009-09-09", you can use strtotime(), which will try to parse many different types of date strings. Learn more about the strtotime function at in the PHP manual. So if I wanted to use PHP to format that date as something different, say to insert into a MySQL database, I would use code that looks something like:

<?php $date = date("Y-m-d H:i:s",strtotime("09/09/2009")); ?>

Which sets date equal to "2009-09-09 00:00:00".

But when you pass a string to strtotime() that the function can’t parse, or try passing a date string directly to date() instead of a timestamp, date() can’t do anything with the invalid value.

Demystifying 12/31/1969 (or 1/1/1970 for Eastern Hemisphere folk)

Since the Unix timestamp is based off the Unix Epoch, an invalid timestamp defaults to to the Epoch (Thu, 01 Jan 1970 00:00:00 +0000).

But, date() displays the formatted time taking into account the timezone of the server or a timezone set with date_default_timezone_set(), so if your timezone is set to something like America/New_York (-0500), the date will be adjusted, resulting in a time that falls during 31 Dec 1969.

So if your server or script timezone is set to a timezone in the Western Hemisphere, any invalid timestamps will end up displayed as some incarnation of 31 Dec 1969. Likewise, in the Eastern Hemisphere, the date falls on or after the Epoch, resulting in a returned value of 1 Jan 1970.

Like Y2K except worse…

The concept of the Unix Epoch as the basis for time is causing some issues as we get deeper into the new millennium. For 32-bit systems, such as this server and hundreds of thousands (likely millions) of other computerized devices out there, time is finite. The systems will not be able to handle the large integer required to store the date based on the Epoch. When Tue, 19 Jan 2038 03:14:07 UTC rolls around, timestamps will rollover—to a value that equates to Fri, 13 Dec 1901 20:45:54 GMT.

As much as I’d like to travel back in time and see the last few days of Queen Victoria’s reign (oh the fashion!), that rollover will likely bring software systems crashing down. In fact, some systems have already started showing issues if they deal with dates farther than 27 years in the future. Luckily, electronics have been on a steady move toward 64-bit systems that can handle dates up to over 200 billion years in the future, but it’s not unlikely that some 32-bit systems will still be in use when 2038 rolls around even if their manufacture has slowed (or likely stopped).

If you’re trying to pass a perfectly valid date that falls before 13 Dec 1901 or later than 19 Jan 2038 to your PHP script, chances are you’ll see this Epoch error, because the server can’t handle that timestamp.

What’s your favorite 12/31/1969 story? Are you worried about the year 2038?

The Many Faces of the Hyperlink

The World Wide Web is built on links. It thrives because links are everywhere. There are links to the various pages on individual sites. There are links from one site to another. There are links in e-mails to websites. There are links in PDFs and documents and presentations to Web pages. Chances are, you used a link to get to this article. Yet, when it comes to setting up a website, styling and consideration of links is often overlooked. Or worse, specific choices for links are made that end up hurting the usability and interaction of your website.

Link states and their selectors

A link isn’t just an element with one look. It has five different states that can be styled with CSS (and to some degree basic HTML, but you should be separating your styling from your content). Here are the different link states and their associated CSS selectors.

a:link
The link state is the basic state for a link. It’s the blue, underlined text default. A link that hasn’t had and isn’t currently having any action on it should look like this.
a:hover
The hover state is what happens when you move your mouse over a link. Typically, this involves a change in color or decoration. The mouse cursor also changes.
a:focus
Perhaps the most often overlooked state, the focus state is to keyboard navigability what the hover state is to mouse users. When a link is focused on using the keyboard, or after being clicked, it will use the definitions of this state to style it. Default styling generally puts a dotted outline around the element.

You can change the color, style and width of dotted outline (or remove it altogether, although that’s not recommended) in CSS with the outline property (ex. outline: #f00 solid thick;). In newer browsers, other elements can have outlines as well (allowing for double borders), although IE will only display an outline on links only.

a:active
The active state controls how the link appears right after being clicked (while the action is taking place, such as requesting a new page). This gives feedback to the user that their click was registered by the browser, and that something is happening, even if it isn’t readily apparent. The default for this is typically a red text color.
a:visited
If a user has viewed the destination page, the link is considered visited. This is important feedback for the user so that they can know which pages on your or external sites they’ve already seen, thus not needing to click on the link. Default styling of visited links usually colors the link an eggplant or dark purple color.

Each one of these selectors should have a different style. Why? It’s all about usability.

Usability

The Internet as we know it—that is, the one available to the public—was born right around 1992. That was 18 years ago. (Think about it, the majority of students in this years incoming college freshman class were born that same year.) In that time, visitors have come to expect certain things on the Web. For instance, what is the first thing that comes to mind when you see blue, underlined text? You said “a link,” didn’t you. Blue, underlined text has become synonymous with a hyperlink. People see it, instantly recognize “ooh, a link!”, then click on it if they think it looks interesting to them. They die a little inside if it doesn’t do anything. They rejoice if it takes them to another page. That is usability.

Usability: the ease with which a visitor can accomplish basic tasks on your site. Navigation is the most basic task on the web, after reading content.

If you’re only willing to put a minimum amount of consideration into link styling in your design or development, the best thing you can do is dont do anything to the browser defaults. Ok, so maybe those colors would be a little difficult to read on say, a black background, but at least users would understand that they’re links.

Users need to know four basic things:

  1. Specific text is actionable (that is, it is a link)
  2. They are hovering or focusing on it (taking action will do something and they’re clicking on what they intend to)
  3. Something is happening once they’ve clicked on it
  4. Whether they’ve already seen the destination

If your link looks like plain text, no one is going to try to click on it. They don’t have any cues to know that they can take action.

If your link doesn’t change when the visitor is hovering or focusing (via keyboard), they can’t be sure that when they click (or hit enter) something is going to happen. What if they do click but cause something else to happen? That’s bad usability. These two states (hover and focus) are perhaps the only two that I can consider ok to have the exact same styling. Both states indicate that pressing a button (on the mouse or keyboard) will activate the link. If you remove the default outline for the focus state, make sure to do something else that makes it very obvious to a keyboard user that the link is being focused on. Some browsers, like older versions of Opera don’t do anything with the focus state, and others, like IE6, end up meshing focus and active together, so having slight differences between hover and focus might be best for browsers that get confused.

If nothing immediately happens when a user clicks, they might think they missed the link or it is broken. They need feedback to know something is happening in the background, especially if it takes a noticeable amount of time to request the new page.

If they’ve seen a page on the site already, they might not want to visit it again right now. Or, if they’re clicking on various links to read after they’ve finished scanning your content, they might want to know if two links go to the same location. If your visited links look exactly the same as unvisited links, users have no indication of this. Give them some.

Consistency

I’m sure plenty of Web designers are cursing at me right now about stifling their creativity, saying “that color scheme looks like total dog-poo with my design.” And I totally understand that sentiment. You can style your links differently than the browser defaults. I do it. But if you do, at least keep it consistent.

If links on your website are say, bold orange text with no underline, people will probably pick up on the fact that bold orange text with no underline are the links on your site. But if you also use bold orange text for some other type of emphasis, people will be confused when they try to click and nothing happens. Or if another link is suddenly italic red text with an underline, they might think they’ve visited the link, or it’s not a link, or who knows what. It’s unlikely that they’ll click on it. Consistency is key. If you want your users to memorize a new paradigm, make sure you always use your new paradigm.

And please, for the sake of all things holy and unholy, don’t use blue, underlined text unless it is a link. (Or if you are a sadistic developer who takes pleasure in frustrating and confusing your users.)

Exceptions to the rule

There are always exceptions to the rule. The major one here has to do with in-site navigation. Obvious site navigation, like menus and footer links can be styled differently than normal hyperlinks. If users expected your navigation to be blue underlined text, the Internet would be a far more homogeneous place, and that would be boring. When you have obvious menus, your users are going to understand that those are links to other pages in your site. But when you have links within your content, they need to know immediately that they are looking at a link.

A side rule to this: don’t link to external sites from your site navigation without clear indication of what is happening. That is really jarring, and a good way to get people away from your website so that they don’t come back. Site nav links should almost never open in a new page, either.

What link styling strategies have you found work best for you?

The TITLE element and jQuery’s text() function

You’re doing it wrong. In a day of zero fun, a coworker and I ended up tasked with debugging a jQuery-based script that seemed to be perfectly fine, except of course, the part where it wasn’t working as expected in IE. After some tracing, it turns out the issue had everything to do with one line of code not returning a value: $("title").text();. To translate, the author of the code had been trying to retrieve the text of the title element using jQuery’s text function. But, turns out that doesn’t work in IE.

The solution

If you want to retrieve the value of the page title, use document.title. If you want to set the value of the page title—the title displayed at the top of the browser—use document.title.

It doesn’t matter if you’re working with straight JavaScript or a library like jQuery, the correct way to interact with the page title is through document.title.

Here’s a full code example:

var foo = document.title;
alert("The title was "+foo);
// on this site, the above alert would read
// "The title was The TITLE element and jQuery’s text() function"
document.title = "Now it’s been changed.";
alert(document.title);
// this alert = "Now it’s been changed"
// the display at the top of the browser changes too

The explanation

Don’t worry, I’m not going to leave you high and dry without explaining why the original approach didn’t work.

The problem exists in IE because IE doesn’t consider the title element to have child nodes. By W3C specs, the title element contains one, and only one child node: a text node. It can not have any child elements. Just the one text node.  But according to IE, that text exists in some strange nebulous state outside of a normal text node. Here’s a code example.

var titles = document.getElementsByTagName("title");
var kids = titles[0].childNodes;
alert(kids.length);

If you run that code in IE, the alert will be 0. In FireFox, Chrome, Safari, Opera, etc, it will return 1, the expected amount.

Breaking down jQuery.text()

So, the reason $("title").text() doesn’t work in IE is because of jQuery.text()’s reliance on children nodes. Let’s take a look at the function (jQuery version 1.4.2, line 3418):

function getText( elems ) {
	var ret = "", elem;
	for ( var i = 0; elems[i]; i++ ) {
		elem = elems[i];
		// Get the text from text nodes and CDATA nodes
		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
			ret += elem.nodeValue;
		// Traverse everything else, except comment nodes
		} else if ( elem.nodeType !== 8 ) {
			ret += getText( elem.childNodes );
		}
	}
	return ret;
}

A quick translation of the code is as follows. The first line of the function sets up a variable ret as an empty string. This variable is the return variable for the function. Then we jump into a loop that goes through each object in the array that was passed in (remember, $("title") will return an array with a single element). For each of these elements it checks whether it is a text node. If it is, it appends the node’s value to the return value (ret). If it is an element, it recursively calls itself on that element, appending the result of the recursive call to the return value. At the end, ret is returned.

But, remember, in IE, the title element has no text node, because there are no child nodes. So what does ret equal? An empty string. The entire for loop is skipped, because elems is empty. It essentially goes straight from declaring ret="" to returning that initial value.

The code continues to work in other browsers because they rightly treat the element as having a single child node—a text node— and that node’s value—the text—is added to ret.

innerText doesn’t work either

Even if you’re using plain JavaScript without a a library, document.title is the way to do this. Typically, to set the text of an element in IE you would use the innerText property, but you shouldn’t do that in this situation. There are a couple reasons for this:

  1. It doesn’t work in IE. In fact, it’s a documented issue dating back to IE 5, maybe earlier. At this point, we have to assume Microsoft has it working as they intend it to.
  2. The innerText property doesn’t work cross browser. In FireFox, you have to use the textContent property. Why bother writing extra code to be cross-browser compatible when document.title will work without issue?

Wrapping it up

Here’s that first script again, showing the correct way to do it:

var foo = document.title;
alert("The title was "+foo);
document.title = "Now it’s been changed.";
alert(document.title);

So now you know why you can’t use jQuery.text() to retrieve the page title. But that’s ok, because doing so would be inefficient anyway when you can just call document.title. Good luck with your dev.

You Are Not a Web Developer

Yes, I’m talking to you, Dreamweaver user. You. Are. Not. A. Web. Developer. You’re just the person that is screwing up the nice, pretty, semantic, standards-based Internet for the rest of us. The one that devalues our hard work with your naive undercutting. The one who makes our life hell when our project managers quote maintenance or design-tweaking projects not realizing that we can’t just reuse your code and keep our dignity intact. You. I really hate you, you MM_preloader using, nested-tables employing you.

But it’s not because you use Dreamweaver. It’s the fact that you use it as a crutch. Yes, you call it a tool.  A great tool that lets you create these awesome sites without knowing how to do any coding. That, my enemy, is a crutch, not a tool. And p.s. your sites aren’t awesome; they’re bloated, inefficient and have nasty, nasty code under the hood because you don’t know the two types of markup that a developer uses daily: CSS and HTML.

Why is it so wrong?

Don’t worry, I’m not going to just berate you and not try to back myself up a bit.

You can’t fix it when it doesn’t work right

So, you tell Dreamweaver to lay something out in a specific way, but then it doesn’t look right in a certain browser. But, you don’t know how to fix the code and make it work right, do you? Yeah, didn’t think so. Don’t get me wrong, developers spend time debugging and don’t always know how to fix it, but we do know what we’re looking at when we take a gander at the code, and can understand what the code is doing when we find a fix from some other resource.

You’re ignoring SEO

Sure, you might be using header tags, and may even have the right meta tags in there. But you’re not coding for search-based optimization. First, your code is bloated. Search engines sometimes parse the first hundred or fewer lines of code, and your bloated code might not have anything of interest until far later in the code. Second, if you are using rollovers or drop-down menus, you’re using code that search engines can’t do anything with. Much of Dreamweaver’s built in code for things like drop-down menus and rollover images is based on JavaScript, even though it’s not generally needed to do either of those things. Both can be accomplished with CSS.

You’re letting your users get bored

Have I mentioned that your code is inefficient and bloated? Yes? Well, I don’t mind saying it again and again and again. Because all that inefficient, bloated code is extra bytes for your users to download. Extra bytes that really increase loading time. People get bored waiting for a site to load. Then they leave. Without seeing your content. In this new world of 2010, where it seems like everyone has mobile Web access, small, efficient sites are back in vogue. Who wants to pull down three different JavaScript libraries and hundreds of extra lines of code on 3G? (Gods forbid a user is still on EDGE) Slow sites mean fewer visitors willing to stick around long enough for the chance to visit. Svelte code is sexy. Your overweight code is as bad as the obesity epidemic plaguing America.

And this point isn’t just true of Dreamweaver-based sites. iLife, Frontpage, Microsoft Word, whatever other WYSIWYG editor du jour you can name… they all create truly horrendous code that is terribly bloated.

Hey Kettle, you’re black!

Yeah, Pot, that’s right, I do use Dreamweaver. Eight hours a day, more or less. But you know, for a while there, I actually forgot it had something called design view, until my preferences got all screwed up and reset themselves, causing a project to load up in design view. That was a shocker. See, I use it because it’s a decent text editor and code completion speeds up development time. It has a built in project system with an FTP tool that keeps me from having to run two or three programs at a time. But ultimately, I use it because it is what is on my system at work.

Curtis McHale said it well in an article reprimanding hiring managers for saying “Dreamweaver users need not apply”:

At my fulltime job it simply comes down to cost. I use Dreamweaver because it is in CS3. There is no real break through feature that I could find to justify to my boss so that they would purchase Coda.

And Curtis is lucky. He posted that over a year ago and had CS3 at work. Here it is Aug. 2010 and I’m still stuck with CS2 at my 9-5. It’s a sore point for me. But hey, I’m employed, I’m not going to complain too awful much. But there’s probably a snowball’s chance in hell that my company is going to pony up cash for a different program.

I could write a site up in Text Edit or Notepad if that is all that was available to me, then pull up an FTP program to upload to the server. It’d decrease my efficiency, but I could do it. But if you’re paying me, don’t you want me to be as efficient with my time as possible? Of course, if you aren’t the company I work for, you’re not paying me to use Dreamweaver because I use Coda at home. But you, you’re not efficient. It takes me less time to type it all out, because I know the code, than it does for you to go through all the WYSIWYG dialogs.

Are you willing to defend Dreamweaver WYSIWYG? Go ahead, play Devil’s advocate in the comments.