Everything In Between

The brutally honest, first-person account of Meitar Moscovitz’s life.

Archive for the ‘JavaScript’ Category

Why CSS needs delegation capabilities and not “variables”

14 comments

It’s been too long since I joined the fun, if amazingly heated, debates over the direction that Web standards are moving in. Recently, given the “free” time to do so, I decided to dive head first into what is (sadly) an almost 14 year old debate. The result is this blog post, which is mostly a response to Bert Bos’s essay Why “variables” in CSS are harmful and Matt Wilcox’s opposing response to that essay, Why CSS needs to borrow from programming languages. Their articles are each worthy of a read, possibly before this one.

Here’s the summary of my argument.

Adding many “programmatic” features to the CSS language such as variables, macros, or flow control is a mistake. However, CSS’s failure to simply encode visual relationships (instead of merely typographic properties)—a severe deficiency in the core language itself—requires the addition of delegation features. With the additional capability to reference an arbitrary element’s computed value regardless of its hierarchical context, CSS will be more accessible to both amateur and professional web designers, more capable, and will more forcefully promote the semantic Web and its ideals.

In this corner: CSS variables are harmful

Bert does a great job of summarizing the conclusion of his argument himself. In his essay, Bert says:

Adding any form of macros or additional scopes and indirections, including symbolic constants, is not just redundant, but changes CSS in ways that make it unsuitable for its intended audience. Given that there is currently no alternative to CSS, these things must not be added.

As we all know, one of the wonderful things about CSS is that the core language itself is remarkably simple. (What’s not simple is the spectacular way browser manufacturers have destroyed everyone’s hope that implementing CSS-based designs in the real world will ever be easy, but that’s a whole different can of worms.) Fundamentally, CSS’s syntax can be explained with a mere three major components: property/value pairs, declaration blocks, and rule sets.

What this means is that CSS as a language is stupidly easy to learn. I think everyone would agree that it’s certainly easier to learn than, say, JavaScript or XSL. Now, that’s important because, without putting too fine a point on it, Bert mentions multiple times that CSS’s “intended audience” are the diverse and likely relatively technically ignorant content authors that are responsible for the overwhelming majority of web pages on the public Internet today.

He makes the very good point that The value of the semantic Web isn’t defined by how well structured the best documents are, but by how well structured the vast majority of documents are. In other words, CSS needs to remain instantly useable and reusable to these untrained, amateur web content publishers for the benefits of self-describing documents (i.e., the semantic Web) to see mass adoption.

To wit:

reusing other people’s style sheets is more difficult if those style sheets contain user-defined names. Class names are an example. Their names may suggest why the author created them (assuming they are in a language you understand), but typically you will have to look at the document to see where they occur and why. Symbolic constants make that problem worse.

And, later:

For many people, style sheets with constants will thus simply not be usable. It is too difficult to look in two places at once, the place where a value is used and the place where it is defined, if you don’t know why the rule is split in this way. Many people are confused by indirection anyway and adding an extra one, in addition to the element and class names, has the same effect as obfuscating the style sheet.

Whether or not you believe Bert Bos is underestimating the average web designer, it’s pretty clear that these are really good points. Nobody wants CSS to be obfuscated, hard to learn, or hard to reuse. That’d just be crazy talk.

In the other corner: CSS variables are a real-world requirement

The more features you add to an application, a programming language, or indeed any software, the more difficult it becomes to grok it. As the Python people would say, the larger a language gets the more difficult it is to hold all of it in your head. Nevertheless, adding “features” is sometimes the only way to add capabilities, and I don’t think anyone in their right mind would argue that, once written, software should never change. (That’d just be crazy talk, too.)

In his opposing arguments, Matt Wilcox recognizes this when he says, Yes, the syntax should be simple, but the capabilities of CSS should not. What he’s alluding to without verbalizing it is the balance between adding necessary capabilities without unnecessarily growing the “size of the language.”

However, Matt says that modern web design methodologies (e.g., separation of concerns between structure, presentation, and behavior) dictate that CSS needs more capabilities than it currently has:

CSS lacks capabilities to allow truly flexible design, requiring layer upon layer of ‘tricks’ to accomplish certain objectives, requiring content to be structured ‘just so’ to achieve a display objective, or in the case of some designs proving instead to be completely incapable.

[…]

CSS’s positioning is a cludge. It’s a cludge because you can only position relative to the last positioned parent container. Well, that limitation in itself dictates that all positioning relies upon how the content is structured. And that means the presentation and the content are not truly separable.

To align CSS’s capabilities with the requirements of real-world web design objectives, he says, CSS needs to be capable of describing relationships between semantically and structurally arbitrary but visually related elements.

Visual design is fundamentally about relationships between elements. For all of the artistic flourishes and creativity, it’s about relationships. ‘That yellow’ only grabs your attention because of its contrasting relationship with ‘that blue’. ‘This heading’ only works as a heading because of it’s exaggerated relationship to the size of the body text. […] CSS has no clue about relationships, period. And that’s why CSS as it stands right now, is not good enough. That’s why CSS without variables (true variables), without basic logic, without maths, can never be as flexible as we need it to be.

This is what web designers have been complaining about for (what feels like hundreds of) years. The fact that CSS has no capability to describe presentational relationships between elements in addition to directly describing an individual element’s presentational properties is a gaping hole that sorely degrades its ability to be a media-agnostic styling language. Every single web designer I’ve worked with has gasped at this omission, and though at first I didn’t understand why, the more I understood the principles behind graphic design the more I came to realize how fundamentally problematic this omission really is.

Adding delegation makes CSS easier for designers

As Matt eloquently stated, design is all about relationships. Good web designers create designs by constructing visual elements that have strong, often exacting relationships with other visual elements. There are many names and examples for this: visual language, visual hierarchy, the golden ratio, the grid, visual balance, the typographer’s scale, and so on.

What happens when the designer tries to define a relationship between elements? “How do I say that the whitespace between element A and element B should always be the same? How do I define element A’s height as half of element B’s?” These definitions, which are natural and necessary to the way designers work in both their mind and their mediums, are impossible to encode in CSS.

The closest you can get is declaring the same values to each element’s properties, not describing the relationship itself. This suffices only so long as these values are known ahead of time and are the same as one another, which severely limits the design possibilities we are capable of (without resorting to what Matt calls “tricks”). That’s why achieving simple visual effects are actually very complex and so, sadly, that’s where you’ll find the majority of indirection and obfuscation in CSS today. (I’m looking at you, faux columns.)

So who wins?

Both Bert Bos and Matt Wilcox have made some great points. Bert rightfully wishes to keep CSS lean and simple, even at the expense of some arguably beneficial styling power. Matt, on the other hand, argues that our needs as web designers have evolved faster than the technology to the point where CSS is too limited, fundamentally so.

The truth is, they’re both right. And they’re both wrong. Or rather, they are each taking a position that is too extreme. Bert’s absolutely correct when says that many of these proposed extensions are redundant and harmful, and yet Matt’s also correct that CSS lacks some fundamental capabilities that designers expect to be present.

Bert says that the CSS capabilities everyone’s asking for can be implemented using techniques that don’t rely on CSS whatsoever. These techniques, he says, make things like true CSS variables “redundant.”

There are examples of CSS with constants to satisfy all styles of programming, e.g.: David Walsh (in PHP), Tedd Sperling (in PHP), Digital Web Magazine (in PHP), Eco Consulting (in SSI), and Christian Heilmann (SSI and PHP).

Quite simply, he’s correct in stating that programmatic features need not be added to CSS proper to achieve desired results, but he’s incorrect in his apparent thinking that designers will be able to use these other tools to leverage CSS. Take, for instance, the probably more familiar (though not linked above) notion of using JavaScript to manipulate CSS values.

var x = document.getElementById('SideBar'); // get #SideBar element
var y = document.getElementById('MainColumn'); // get #MainColumn
var z = document.defaultView.getComputedStyle(y, '').getPropertyValue('height'); // get computed height of #MainColumn
x.style.height = ( parseInt(z) / 2 ) + 'px'; // set #SideBar's height 1/2 of #MainColumn's

This is an example of programmatic code that uses variables and expressions. It sets the element with the ID of SideBar to half the pixel height of the element with the ID of MainColumn. It does this by obtaining the MainColumn’s height (at the time this code runs) and saving it in a variable, then performs some trivial math to half the value and use the result as the pixel height of the SideBar.

Doing this is currently impossible with CSS alone, yet it’s something that clearly belongs with whatever other “presentational” code exists and not in “programmatic” scripts that would otherwise be charged with defining “functionality.” As Matt states, using JavaScript to “script” solutions to CSS’s shortcomings like this is not an acceptable answer.

CSS doesn’t have [basic logic or maths]. Nor is it the job of JavaScript to make up for this lack of abilities. JavaScript is about interaction behaviour, and what we are talking about here is pure display logic. Not interaction logic.

Moreover, the place designers expect to put code like this is, of course, into a CSS style sheet. The way designers expect to put code like this into CSS is by adding delegation features. Requiring designers to learn JavaScript (or any other programming language) to encode such design relationships is nothing short of ridiculous. In what world is that easier for untrained laymen to understand than CSS?

Adding delegation to CSS is worth the effort

One of Bert’s arguments against such additions to CSS is that implementations would become harder to create, and that we’ll (almost certainly) see more bugs.

extending CSS makes implementing more difficult and programs bigger, which leads to fewer implementations and more bugs. That has to be balanced against the usefulness of the extension.

Although I do agree with his statement that an extension’s usefulness has to be balanced against its potential costs, I think something so fundamental to design methodology as delegation greatly overcompensates for the cost of such implementation efforts. Moreover, if I understand Bert correctly and as he also discusses, the majority of implementations that would need to implement such delegation already have relatively complex internal structures to make the implementation effort somewhat easier:

There is no scoping [in proposals that only define global constants]. That means that an implementation needs a symbol table, but no stack. A stack would require a little bit more memory, but mostly it would make implementations more complex. (Although every programmer has, one hopes, learnt to program a symbol table with lexical scope during his training.) Constants in CSS are thus easier than, e.g., XML Namespaces, which are lexically scoped.

It is different for those CSS implementations that provide a CSS Object Model (an API for manipulating a style sheet in memory). Those implementations do need to keep track of scope in some way, because adding or removing a line of the style sheet can make a previously redundant definition become meaningful.

In order to use JavaScript to solve many of the shortcomings of CSS, as huge numbers of professional web developers do routinely, we use the very CSS Object Model whose prior implementation already exists for us to build upon.

CSS delegation doesn’t grow the size of the language

For the sake of argument, let’s simplify our requirement somewhat so that our somewhat contrived example of design intent is to create a relationship between the MainColumn and the SideBar elements such that they are of equal height. This is more informally known as “making columns.”

Here’s what a natural, hypothetical snippet of CSS would look like if the language supported delegation features such that it could encode visual relationships.

#SideBar { height: #MainColumn; }

This code theoretically says almost the exact same thing as the JavaScript shown earlier (save for the division, of course); it takes the computed value of the MainColumn element’s height property and applies that value to the SideBar element’s height property. In other words, “The SideBar’s (element B’s) height is always the same as the MainColumn’s (element A’s).” (Of course, this is a parse error in reality today.)

This extremely trivial example has some remarkably far-reaching implications, and yet there is really nothing radical about its syntax. Making this a reality significantly expands the capabilities of CSS without dramatically increasing the size of the language. This capability would not only beat the pants offCSS tables,” it also potentially obsoletes the arguably misguided efforts of the CSS3 Advanced Layout and Grid Positioning modules, too.

We’ve long since abandoned table layouts because they force us to use presentational markup. That’s still what “CSS tables” force us to do, too. In other words, with display: table, the SideBar needs to be a child of the MainColumn element or, maybe worse and more likely, a child of a semantically meaningless wrapper element.

CSS positioning was introduced with the promise of freeing us from source-order-dependent styling, without which there is no hope of efficiently abstracting presentation away from structure. Moreover, abstracting presentation away from structure is the single most important prerequisite needed to improve document reusability and strengthen the semantic Web. Absolute positioning works, but limitations elsewhere in CSS mean its use is problematic for many designs, so in practice it doesn’t gain widespread adoption.

Here’s a theoretical solution to a two-column and a footer layout using CSS delegation with this semantic HTML:

<body>
    <div id="MainColumn">I'm the main column.</div>
    <div id="SideBar">I'm the right-hand sidebar.</div>
    <div id="Legalese">No one will read me.</div>
</body>

The CSS would look extremely familiar, possibly like this:

#MainColumn { margin: 0 25% 1em 0; float: left; }
#SideBar { width: 25%; min-height: #MainColumn; }

Using the same HTML, the same solution using the CSS3 Advanced Layout module would look something more like this, although to be frank I’m not certain I fully understand this syntax even after staring at it for months:

body {
    display: "a  b"
             ".  ." /1em
             "c  c"
             75% 25%
}
#MainColumn { position: a; }
#SideBar { position: b; }
#Legalese { position: c; }

Not only does there seem to me to be far more indirection in this method than there would be using CSS delegation, there is also an enormous increase to the size of the CSS language: a new (ASCII-art?!) value to the display property whose syntax is clunky at best. A similar story can be said of the CSS3 Grid Positioning module, which does lots more than just add a new (already complex) gr CSS unit.

The upshot is that the Advanced Layout and the Grid Positioning modules are doing some of the right things in many of the wrong ways. Both those modules add unnecessary complexity to CSS without giving designers a natural way to say what they mean. They do more to introduce obfuscation and indirection than simple delegation would, and they aren’t as broadly capable. Both of them try to solve a specific problem instead of dealing with fundamental deficiencies in the toolset designer’s have to work with.

Designers want relationships via delegation, not variables

Adding delegation such as that I’ve just shown is a natural, necessary addition to CSS because it is how designers create visual components—such as grids—in their designs. Variables (and constants, and macros, etc.), which simply reuse and modify pre-defined statements aren’t what designers care about. Adding them will bloat CSS without adding useful functionality.

“Okay,” you may be saying to yourself, “but delegation is itself a kind of variable, isn’t it?” Technically yes, however adding delegation resolves the core deficiency in the CSS language that designers need to use every day. Yes, it’s technically a form of variable, but that’s not how designers think of it. To say that one element’s visual properties is like another makes a variable only by creating a logical and visually appropriate mapping from the first element’s property to the second independent of markup, thereby avoiding indirection in the form of a variable name or other unfamiliar symbol.

Delegation like this doesn’t require the addition of anything other than what already exists in CSS. Class names and ID values are identifiers whose indirection people already have to deal with. Using them for delegation (to reference another element’s style) doesn’t increase the cognitive load any more than using them to reference HTML elements does. Though untested, the cognitive load might actually be even less since the CSS delegation’s references could be in the same (style sheet) file.

Moreover, delegation will increase the likelihood of document reusability by enabling style sheets to be more self-describing, more self-referential, in a similar way as good markup is. It satisfies a very fundamental need that designers have to define graphical relationships between elements. At the same time, it does so in a way that is natural to both their way of thinking and beneficial to the separation of concerns principle on which the “web stack” (the trifecta of HTML, CSS, and JavaScript) is based.

Written by Meitar

December 14th, 2008 at 2:55 am

How web designers can do their own HTML/CSS: Read Foundation Website Creation

5 comments

Last month, 37signals published a short but sweet post about why web designers should do the HTML/CSS implementations for their own designs. The bottom line is, as we’ve all been saying for a long time now, that the Web is not the same kind of medium as other mediums like print. It is a fundamentally different kind of canvas than most web designers are used to using. As a result, if you as a web designer are not intimately familiar with it, you’re not going to do great work.

designing for the web is a lot less about making something dazzle and a lot more about making it work. The design decisions that matter pertain directly to the constraints of the materials. What form elements to use. What font sizes. What composition. What flow. Those decisions are poorly made at an arm’s length.

I’ve worked with many web designers in the past who only did abstractions and then handed over pictures to be chopped and implemented by “HTML monkeys”. It never really gelled well. The things that got strong attention were all the things that Photoshop did well. Imagery, curvy lines, and the frame. All the around stuff, never the it stuff.

In other words, to do great web design you have to design in the Web, not in some other medium for the Web. I mean, serious magazine firm employs designers who don’t understand how to work with page layout programs like InDesign. Why, then, do so many web design agencies employ designers who don’t know how to work with web technologies, or even how to use programs like Dreamweaver? It doesn’t really make any sense, and it’s no wonder that the resulting implementation is rarely top-notch work.

But if you’re a graphic designer who doesn’t know much about Web technologies, what are you to do? Well, as a first step, I think you should pick up my new book, Foundation Website Creation. It’s available from all good booksellers (and probably some crappy ones) as of today. The book is targeted towards all manner of web professionals, including graphic designers and website producers, who want to learn more about what it takes to actually implement a site.

If I do say so myself, the chapters on XHTML and CSS are exceptionally thorough. The book doesn’t try to turn you into an exceptional programmer. Instead, it will explain the foundational concepts you need to know to understand how XHTML and CSS actually work, and in so doing will enable you to use the tools you already know to solve problems and get things done.

I think this book will be an excellent starting point for lots of designers and other web professionals. However, it is not going to take you from zero to hero—no book can. That’s why I recommend that, after you read Foundation Website Creation and have a solid grasp of what the technology can do for you and how it actually does it, you next take a look at these excellent books:

  • DOM Scripting by Jeremy Keith — if you’re a designer that needs to add a behavioral layer with JavaScript and Ajax to your pages, you need to read this book next.
  • Mastering CSS with Dreamweaver CS3 – if you’re familiar with Dreamweaver and want to keep using it to create standards-based web sites, then I recommend you follow Foundation Website Creation with this book by Stephanie Sullivan and Greg Rewis to take your Dreamweaver skills to the next level.

As always, most of all, have fun. Because if you’re not having fun, you’re not going to make good web sites no matter what you know.

Note: As of this writing, the book listing on Amazon still publishes the wrong author list, which is very frustrating but out of my hands. At least the image of our book’s front cover lists the correct authors.

Ridiculously simple JavaScript version string to object parser

one comment

In any kind of development, you often have to deal with version strings. Typically, these version strings are just a dot-separated list of numbers that represent different versions of the software. I recently had a need to compare two version numbers against one another to determine which one was newer. This is useful if, say, you’re building an application that wants to check its current version against the “latest” available version.

In JavaScript, this is thankfully pretty trivial. My solution is to just parse the version strings with a simple function and return them as objects with appropriate properties whose values are integers. Once in this form, we can compare them with simple math.

function parseVersionString (str) {
    if (typeof(str) != 'string') { return false; }
    var x = str.split('.');
    // parse from string or default to 0 if can't parse
    var maj = parseInt(x[0]) || 0;
    var min = parseInt(x[1]) || 0;
    var pat = parseInt(x[2]) || 0;
    return {
        major: maj,
        minor: min,
        patch: pat
    }
}

Using this new object, we can now compare two versions really simply:

var running_version = parseVersionString('3.5.2');
var latest_version = parseVersionString('3.4.5');
if (running_version.major < latest_version.major) {
    // A major new update is available!
} else if (running_version.minor < latest_version.minor || running_version.patch < latest_version.patch) {
    // A new minor or patch update is available.
} else {
    // We are running the latest version! No need to update.
}

Written by Meitar

June 15th, 2008 at 5:39 am

I’m getting a book published and it’s called Foundation Website Creation

9 comments

For those who have been wondering what is keeping me so busy these days, the answer is that I’m working on the final stages of a book that is getting published as one of three co-authors. Not only am contributing three chapters (the technical chapters on (X)HTML and CSS, specifically), but I am also technically reviewing the entire book.

My co-authors on the book, called Foundation Web Standards Foundation Website Creation (you can pre-order now) and published by Friends of ED, an Apress company, are Jonathan Lane of Industry Interactive, Inc. and Joe Lewis, who blogs at Sanbeiji.com. I’m not going to say much more until after the book is released in late July.

For the eager, here’s the description of the book posted on the Friends of ED website:

Foundation Website Creation explores the process of constructing a web site from start to finish. There is more to the process than just knowing HTML! Designers and developers must follow a proper process to flush out goals and objectives and determine requirements both prior to, and during project development.

Large Web projects are rarely completed by a single person. Producers, project managers, designers, developers, writers, and editors all play critical parts in a project’s evolution. This book provides an overview of the entire process, and also shows project development from the perspective of these different roles. It introduces the key concepts and duties performed by every member of such a team, and gives you the skills necessary to tackle projects like a professional.

It’s quite exciting getting a book out, and it’s quite a bit more work than I’d have ever originally thought. That being said, it’s extremely rewarding. There’s a lot more work I need to do on it between now and the time it gets released to publishing, so, well…back to work I go.

Now you all know where I’ve been spending my time writing.

The 10 Geekiest Leopard Features I Will Probably Love

one comment

This is already horribly old news, and by old I mean several days ago since that’s about as fast as it takes technology news to grow old, but Apple is releasing Mac OS X 10.5 “Leopard” at the end of this month. Apple is calling this release a “major upgrade,” and indeed Apple has rarely made its users wait so long between operating system releases as they have done between Tiger (Mac OS X 10.4) and Leopard. So, I’m already excited.

But then today I was glossing over Apple’s featured features list and I got even more excited. There are the usual, largely meaningless, fluff updates that are nice for Joe Schmo or his mother, but that power users simply don’t care about, like the new iChat support for animated buddy icons, but the list is also chock-full of really cool, really useful features.

What’s interesting is that a good deal of these features aren’t really new features at all. For instance, if you knew how to manipulate the NetInfo database on your Mac, you could already share any folder via Apple’s “Personal File Sharing” feature. (Here’s a Mac OS X Hints hint explaining how to do it.) In Leopard, however, Apple claims that this functionality is now integrated straight into a folder’s Get Info… window. If it works as smoothly as Apple claims, this is finally going to bring Mac OS X (client) into decent competition with Windows XP Professional in terms of GUI-level power-user features.

However, while all of these features are really cool, here’s a list of the ten geekiest features I will probably absolutely love, for one reason or another.

  • Ruby on Rails, out of the boxThe hot thing in web development right now is Ruby on Rails. Macs have already been the best personal desktop and web development platform because they have built-in support for the Apache web server and a host of other features, but now they will come with a ready-to-roll installation of Ruby on Rails, sporting Mongrel and (better yet) Capistrano! Specifically with the addition of Capistrano, which is terribly undersold as simply a Ruby on Rails deployment platform, these UNIX-y “toolbox” items are bound to make Macs that much more useful right out of the box.
  • Safari’s full history search — As their recent public partnerships with Google have shown, Apple is very clearly invested in search technologies. Spotlight gets a huge number of improvements in Leopard, but none which I think are going to be more useful to more people than this one: spotlight searches on the full text of each web page in your visited history list. That’s just awesome. Also awesome: using spotlight as a calculator and as a dictionary, which also shows just how Google-like Apple is trying to be. (Google also lets you ask it arithmetic questions and a dictionary.)
  • Wikipedia articles in Dictionary.app — I love Wikipedia because it’s one of the fastest ways to get (relatively) reliable information quickly. Now that Dictionary.app has built-in integration with Wikipedia, imagine the possibilities for getting that knowledge instant-gratification craving fixed. Apple has not yet announced this capability, but I can easily envision a scenario where all Cocoa text fields are instantly “wikified” (with text that matches Wikipedia articles highlighted) much in the same way that current Cocoa text fields allow you to right-click on a misspelled word and have it corrected by Dictionary.app.
  • Application-based firewall — In classic Apple fashion, functionality that was previously available via third-party additions is now available from Apple itself. In this case, I have to wonder how well Apple’s updates to its firewall will obviate the need for Little Snitch, which is basically an application-based firewall, too, and a good one at that.
  • Built-in guest log-in account — If you’re as paranoid about security as I am, you’ve already created a special, limited-access user on your system (called Guest or Visitor or whatever) and whenever friends are over, you tell them to use that account instead of your own. Now in Leopard, Apple has gone through the trouble of setting this up for us already. A small change that is going to have a big impact.
  • Scriptable System Preferences & applications — With AppleScript, you can automate the things your computer does with scripts, as long as those things are “scriptable.” In previous versions of Mac OS X, huge gaping holes of what things shipped by Apple were scriptable existed, causing me (personally) some really annoying headaches. AppleScript GUI scripting helped me get around many of those roadblocks, but now it seems Apple is finally filling in some of the most notorious gaps in this functionality with scriptable System Preferences. Yay!
  • Automator workflow variables — Automator brings the power of AppleScript I just mentioned to more people with a completely graphic programming environment. There is no need to open up a text document and write AppleScript code because Automator lets you create a script (called a Workflow in Automator jargon) using your mouse by dragging and dropping actions into the order you want them to be performed. It’s very slick, but until now it’s been very limited. With Leopard, Apple is beefing up Automator so that it includes things like variables, basic programmatic capability that was sorely lacking before. (Also majorly cool: a command-line utility to access Automator!)
  • Finder.app’s path bar — Every serious Mac user knows that the Finder needs a lot of help. Now, it’s getting some. Something the Windows Explorer has had forever (as had every desktop environment for Linux, of course) is a visual cue to show you where in your filesystem tree a given folder is located when you are viewing said folder. Now the Finder gains this capability (though Apple’s description implies that it’s going to be off by default) with what Apple is calling a “Path Bar”. Finally!
  • Cocoa and scripting bridges — Even though no one really seems to know about it, it has long been possible for languages other than AppleScript to do things like send Apple Events to Mac OS X applications. Specifically, Ruby and JavaScript, two of the most well-known web development languages in existence, can already do this with a single ScriptingAddition (OSAX). But now Apple is making this functionality a central feature and fully extending it to their Objective-C (and Cocoa) language and applications such as Xcode and Interface Builder. This means people like me will have a shallower learning curve before we’re able to create full-fledged, native Mac OS X applications. Now that’s exciting!
  • Xcode 3 refactoring — This is something you kind of have to see to believe. I got the opportunity to see it demoed at Apple’s Leopard Tech Talks last year and I was really excited by it. With the new Xcode, Apple’s development IDE, you can do away with find-and-replace searches for things like renaming functions because Xcode understands what parts of your code are what structures and, when you tell it to “change the function named myFunction to myNewFunction,” it’ll only find-and-replace function names instead of every instance of the string “myFunction.” That’s pretty big, and if it were available for more languages, it’s almost enough to make me ditch vim.

So there you have it. Ten features you might not have already known about that are some of the most promising features I can see in Leopard. And I didn’t even get into Wide-Area Bonjour, which could make services like DynDNS or No-IP a thing of the past (and which I still want to learn more about), or the new Terminal application (finally with tabs!), or even the multiple user certificates for S/MIME encrypted email.

Note: One of the least known security features available on Mac OS X is also possibly one of the best, and the simplest. Evidently, all Intel-based Macs are shipped with the XD (aka. NX, aka. DEP) bit turned on—and thankfully there doesn’t seem to be any way for users to turn it off. However, this isn’t a silver bullet and if you want to learn why you should check out this excellent Anandtech article: A Bit About the NX Bit.

Written by Meitar

October 18th, 2007 at 10:45 am

Window and Element Resizing Annoyances in Internet Explorer

leave a comment

This has been an interesting day. In less than 8 hours, I’ve had to tackle the following IE nuisances:

document.body vs. document.documentElement

In IE 6, in order to access the current width of the window in JavaScript you need to get document.body.clientWidth only if you’re in quirks mode. If you’re in standards mode, this property not only still exists, but it means something entirely different! It instead refers to the width of the body element.

This causes real trouble for some scripts when the value of the this variable seems to suddenly become frozen or fixed at a single value instead of changing appropriately on a window resize event. Instead of document.body.clientWidth, in standards mode, use document.documentElement.clientWidth. (Reference table at QuirksMode.org)

Internet Explorer crashes when attempting min-width

If you use IE’s proprietary expression() syntax to script a CSS value, beware of calculating widths or heights that exactly match the value you’d like to set. If you do something like the following to set a minimum width on #someElement, IE will crash when you actually resize that element to be 500 pixels wide.

#someElement { width: expression(document.body.clientWidth < 500 ? "500px" : "auto"); }

Instead of doing the above, you should check for almost exactly the size you want, like so:

#someElement { width: expression(document.body.clientWidth < 501 ? "500px" : "auto"); }

However, the really important thing to keep in mind is that the minimum width you’re testing (501 in that second case) needs to be at least one pixel greater than the total content and padding width of the element. So if you have an element that needs to be no less than 500 pixels wide but also has 10 pixels of left and right padding, you need to check not for 501 pixels in width, but rather for 521 pixels in width. (Reference on CameronMoll.com.)

Written by Meitar

May 24th, 2007 at 5:30 pm

Posted in CSS, JavaScript, Web Design

The Web is My Computer To Go

leave a comment

The other day my friend bought her first Mac. She was clearly excited but also clearly a little worried. This, she knew, was going to be a really big change. Or was it?

It occured to me while thinking about what this experience must be like for her, a smart but not technically experienced individual, that in fact a lot of what would be easy on the Mac would be the Web. Why? Because the Web is everywhere and, increasingly, every thing. The Web is the interface most people think about these days when they think about using computers.

Just take a look around. Almost everything you can do on a standard desktop application you can do on web pages these days. Instant Messaging was one of the first applications I can think of (off the top of my head) that was taken to the Web with AOL Instant Messenger’s AIM Express. Yahoo! quickly followed. I remember the days when hanging around in Yahoo Clubs Chat Rooms (now Yahoo Groups, and no longer involved with the Chat Rooms feature) used to be all the rage. I played a ton of Go and Battleship back then.

These days, more and more information is being put online and is becoming easier (and more consistent) to access. Twitter is all the rage, I do all my banking online (over verified HTTPS connections, of course), and Google has integrated GoogleTalk right into the GMail window. In fact, most of my friends never close their GMail window anymore. The browser is the new IM client.

Of course, there’s a fascinating paradox that’s worth examining in all of this. Simultaneously, the Web provides a consistent interface to my stuff (like email or banking information) and yet all of my information is consistently displayed differently. The Web is my computer—to go.

So if the Web is my computer on a take-out menu, the web browser is more and more like its own little computer inside the bigger one. Indeed, AJAX has proven itself in an ever increasing number of applications, and intelligent JavaScript is finally getting the attention it deserves. If you’ll forgive the exceptionally Mac-centric analogy, JavaScript is to the Web as AppleScript is to the Mac. Case in point, here’s a JavaScript bookmarklet that will give you a “full screen” button in any compliant Web browser:

javascript:self.moveTo(0,0);self.resizeTo(screen.availwidth,screen.availHeight);

This illustrates the point that the Web browser is becoming an ever more complex platform in its own right. People have already taken this concept further and more than a dozen Web Operating Systems are already in development. When these mature, computing, for many people, will have finally come full circle and returned to the days of dumb terminals.

By the way, my friend’s doing quite well with her Mac today. She’s even using Safari instead of Firefox these days.

Written by Meitar

April 24th, 2007 at 11:50 am

Greasemonkey Scriptlet for WordPress Comment Moderation

2 comments

It’s Spam Season again, apparently. This means lots of annoying spam comments on my blogs and more time than I’d have liked trying to get rid of them. One little nuisance in particular had been a pain in my neck for two days, and yesterday I finally decided to ease the burden.

When WordPress 1.2’s built-in comment moderation system catches comments it thinks are spam, it sends these comments off into the moderation queue. There the comment can be reviewed, and appropriate action (accept the comment, delete the comment, or ignore the comment and leave it in the moderation queue) can be taken. In order to act on multiple comments at a time (since spam travel in packs), a “bulk action” radio button can be pressed for each comment one wants to peform the selected action upon. Trouble is, when there are 229 spam comments in your moderation queue, this means you have to press 229 radio buttons.

There has to be a better way. Enter Greasemonkey, stage left. From its web site:

Greasemonkey is a Firefox extension which lets you to add bits of DHTML (“user scripts”) to any web page to change its behavior. In much the same way that user CSS lets you take control of a web page’s style, user scripts let you easily control any aspect of a web page’s design or interaction.

Long story short, I wrote a tiny Greasemonkey scriptlet called WP-Delete Moderated Comments which will automatically set WordPress’s comment moderation radio buttons to “delete” rather than “do nothing.” As a result, instead of clicking the mouse 229 times, I merely have to click once on the submit button. Here it is:

// ==UserScript==
// @name           WP-Delete Moderated Comments
// @description    Sets all moderated comments caught in WordPress to be deleted. (Tested with WordPress 1.2 Mingus.)
// @author         Meitar Moscovitz ( http://maymay.net/ ) Copyright 2005
// @include        Change this to your WordPress blog's comment moderation page.
// ==/UserScript==

(function () {
    var e = document.getElementsByTagName('input');
    for (var i=0; i<e.length; i++)
    {
        if (e[i].type == 'radio' && e[i].value == 'delete' && e[i].defaultChecked == false)
        {
            e[i].checked = true;
        }
    }
})();

For those of you who already have Greasemonkey installed, you can install WP-Delete Moderated Comments right now. (Right-click on the link and select “Install User Script…” from the contextual menu. Then change the included page to the appropriate address, as instructed.)

Questions, comments, suggestions and any other feedback are all welcome.

Note: This scriptlet only works for WordPress 1.2 Mingus. No future updates are planned because this functionality is already available in the WordPress core for versions 1.5 and greater.

Written by Meitar

June 25th, 2005 at 12:22 am

Baffling IE Behavior with PNG Opacity Fix

one comment

This has been baffling me to no end for the past few days. I’ve exhausted my own skill to figure the problem out, so I’m putting it up here in the hopes that someone more knowledgeable than I can solve the puzzle.

The other day I was browsing message board posts and someone was asking for information on how to get Internet Explorer to play nice with variable opacity PNG images. I suggested that she try Andrew Gregory’s Improved PNG Behavior file for IE which the poster did. However, she reported the most unusual thing: when implemented on her page, all of her images vanished from view!

Puzzled, I made my own (very ugly) test pages for three different versions of the behavior file. Surprisingly, when I tested Andrew’s behavior file the PNG image on my page vanished too! So I dove into the the code and traced the problem down to line 54 of his file, which reads: element.runtimeStyle.filter = ''; // remove filter.

Commenting that line out solved the disappearing image problem, but it seemed like a messy hack more than a fix. I had to assume he put the line in there for a reason. So I decided to litter the functions in the file with alert()’s to help me visualize the problem. Then I noticed the most bizarre thing. Inside the fixImage() function, both the if block and the else block were executing procedurally. That is, first the statements in the if block executed and applied the appropriate IE filter to the PNG image, but then the else block was executing right afterwards and was removing the filter even though the if block had evaluated to a boolean true!

Here is the relevant code I was working with (some comments, and the alert()s added by me):

function fixImage() {
  // check for real change
  if (realSrc && (element.src == realSrc) && IS_PNG.test(element.src)) {
    element.src = blankSrc;
    alert("element.src set to " + blankSrc); // help debug
  } else {
    if (element.src != blankSrc) {
      // backup old src
      realSrc = element.src;
    }
    // test for png
    if (realSrc && IS_PNG.test(realSrc)) {
      alert("fixImage() 'test for png' IF statement executing"); // help debug
      element.src = blankSrc;
      element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + realSrc + "',sizingMethod='scale')";
    } else {
/*
?? It apparently causes any fix[ed]Image() to disappear! Not sure why it even executes,
?? because the if block above executes too...and doesn't that mean that the else
?? statement should not execute?!?!
*/
      alert("Inside fixImage() 'test for png' else statement: removing filter..."); // help debug
      element.runtimeStyle.filter = ''; // remove filter
    }
  }
}

So now I’m really puzzled. What’s going on? I emailed Andrew on the matter and he said that he couldn’t replicate this behavior. I am testing this in the latest Internet Explorer 6 on Windows XP Home with Service Pack 2 installed. (Or, to be completely anally retentive, version 6.0.2900.2180.xpsp_sp2_rtm.040803-2158 as reported by Help → About Internet Explorer.) He was using the latest IE 6 on Windows 2000, however, so maybe the two versions are different somehow.

All the code is in my PNG test directory and the relevant page is the improved_pngtest.html document. The .htc file is called from within that document. If anyone out there is bored or wants to try figuring out what’s happening in IE, I’d be very interested to hear about your findings.

I should also point out that Andrew has updated and re-written some parts of this function his new file works without any problems even on my configuration. I’d still like to figure out why IE is executing else statements after their respective if blocks have executed though.

Written by Meitar

October 22nd, 2004 at 1:57 am

Posted in JavaScript

Keeping Presentation out of Behavioral JavaScripting

leave a comment

Lately I’ve been working on a personal project of mine, redesigning and revitilizing my website about Bipolar Disorder. It’s still deeply entrenched in the redesign and I’m not even done with the site templates yet, but I was anxious to get some content rolling out quickly so I went ahead with it anyway.

Some elements of the design, however, relied on dynamic scripting to style appropriately. The key thing here, however, is that I wanted to avoid accessing or manipulating style elements from within the JavaScript script. In other words, I wanted to ensure that all my style rules, the visual declarations for the presentation of these links, would be kept in the site’s CSS.

There were several reasons for this:

  1. To keep presentation clearly separated from behavior and structure.
  2. To keep the JavaScript unobtrusive and portable.
  3. To ensure that both aspects, presentation and behavior could be easily updated or altered in the future.
  4. To allow for various styling without touching the script.

Typically, a JavaScript script with a line similar to elem.style.property = 'value'; is used to create so-called “dynamic styles.” Unfortunately, this would not do for me.

So I fiddled and found that the best way to go about this was to simply tag links that I wanted to style by adding a word to their class name and then write styles for the selected elements inside my stylesheets. In effect, links in my page will be transformed from <a href="http://some.other.site/"></a> to <a class="external" href="http://some.other.site/"></a> So I sat down and wrote this little plug-and-play JavaScript to tag the links I wanted. Let’s go over it line-by-line. (If you’re antsy, here’s the whole script.)

First, we define a function named catchExternalLinks. Then we set a variable, extClassName, to hold the class name we’re going to add to the links. While not strictly necessary to hold in a variable, it does make for easy editing later. Don’t like the word “external” for a class name? Change it to something else.

function catchExternalLinks()
{
    var extClassName = 'external';

Next, we do some object detection. This is to ensure that the browser can handle what we’re going to ask of it. Browsers that can’t handle it won’t try to, which is good because it means visitors won’t see an error when they visit the site. They just won’t see the dynamic styling.

if (document.links && document.getElementById) {

Now that we know we’re talking only to browsers which can handle our instructions, we define a variable, h (for host), which will store the beginning of the web address that we’re at. On www.maymay.net, h now contains the string http://www.maymay.net.

var h = window.location.protocol + '//' + window.location.host;

Next, we need to gather all the links in our page. We assign the links array to the variable l.

var l = document.links;

We need to work with each link separately, so we loop through the links…

for (var i = 0; i < l.length; i++) {

…and assign the value of the href property to the target variable after turning the string toLowerCase text.

var target = l[i].href.toLowerCase();

We only want to work with real links, so first we make sure we’re not dealing with javascript: directives.

if (target.substr(0, 11) != 'javascript:') {

Then we search the target string of the link for the h string. If we don’t find it…

if (target.substr(0, h.length).indexOf(h) == -1) {

…then this link is an external link so we tag it as such by adding the extClassName to its className preceded by a space. We do this instead of using setAttribute() because this way we can keep any pre-existing values for the class attribute already in the link. The key here is to know that className accesses the class attribute of an element.

    l[i].className += ' ' + extClassName;}

Finally, after closing all our blocks properly, we set the catchExternalLinks function to execute onload.

            }
        }
    }
}
window.onload = catchExternalLinks;

Of course, as per the requirements for this script being as unobtrusive as possible, it won’t do anything to the style properties of the link. All it did was add a class value, so we’ll need to declare our styles in our stylesheet. In my CSS page, I write the following to display a little icon for these links.

a.external {
    padding-right: 15px;
    background: transparent url(extlink.gif) center right no-repeat;
}

The styling possibilities are really rather endless now. Since I can instantly identify external links via the class external, I can also write context-specific styles. For instance, I can limit my styles to only one part of the page with a selector such as

#main a.external { ... }

or I could write different styles for external links for the sidebar and a comment on my entry with

#sidebar a.external { ... }
.blogComment a.external { ... }

or any other styling I see fit. In addition, from the script, it’s very easy to test for links that meet a specific criteria, say, Google definition searches, simply by adding another if clause inside the main loop. Here’s a version that does just that.

All together, it goes like this:

function catchExternalLinks()
{
    var extClassName = 'external';  // the class to set for external links
    var defClassName = 'defSearch'; // the class to set for definition searches
    if (document.links && document.getElementById)
    {
        var h = window.location.protocol + '//' + window.location.host;
        var l = document.links;
        for (var i = 0; i < l.length; i++)
        {
            var target = l[i].href.toLowerCase();
            if (target.substr(0, 11) != 'javascript:') // only work on links that aren't JavaScript directives
            {
                // tag external links
                if (target.substr(0, h.length).indexOf(h) == -1)
                {
                    l[i].className += ' ' + extClassName;
                }
                // tag Google definition search links
                var anchor = l[i].childNodes[0].nodeValue; // anchor now contains the anchor text of the link
                var s = '?q=define:' + anchor;
                if (target.substr(0, target.length).indexOf(s) != -1) // use != to ensure that the string (var s) EXISTS in target
                {
                    l[i].className += ' ' + defClassName;
                    l[i].title = 'Definitions for ' + anchor + ' on the Web.'; // for the link tooltip
                }
            }
        }
    }
}
window.onload = catchExternalLinks;

Feel free to steal this snippet. Just remember to write your styles in a stylesheet that you connect to your page, or the script won’t have any noticeable effect. Of course, that’s the whole point. Enjoy! ;)

Written by Meitar

September 22nd, 2004 at 9:02 am

Posted in CSS, JavaScript, Web Design