RSS
 

eBay’s policies for JavaScript in listings need to change

24 Feb

I rarely list on eBay myself, but I have some close relatives and friends who run their own eBay stores. They often ask me to write a little bit of JavaScript to spruce up their listings. I have a fair bit of experience working with the various eBay APIs, but when it comes to writing scripts that run on the site itself, it gets very frustrating.

Read the rest of this entry »

 
 

ECMAScript Harmony’s arrow functions

05 Jun

After being out of the loop for quite a while for personal reasons, I got around to getting myself back up to date. One thing I’ve been playing around with is Spidermonkey’s implementation of new ECMAScript features introduced in the 6th edition draft specification.

When I first read the proposals for arrow functions a couple of years ago, I was put off quite a lot by the syntax and I just thought of it as something impure that CoffeeScript developers were trying to force into the language. Maybe I’m a little more open-minded now because, after actually getting to use them, my mind has changed completely. I think the new syntax is beautifully concise, and the real issues that arrow functions solve make it more than worth the short amount of time you’ll need to get acquainted with them. Take the following example:

    // Numerical sort, the old way
    someArray.sort(function (a, b) { return a - b });

    // The new way
    someArray.sort((a, b) => a - b);

It’s not just about saving bytes, though. Arrow functions offer an extra conveniences: no prototype property, internal [[Construct]] method, and lexical this. This means that an error is thrown if they are used with the new operator, and the value of this is fixed to whatever it is in the parent scope:

    // This will cause an error
    new (() => {});

    // `this` inside the timeout function is myObj
    var myObj = {
        myFunction: function () {
            setTimeout(() => alert(this.myProperty), 500);
        },
        myProperty: 'Hello!'
    };

    myObj.myFunction();
    // alert: 'Hello'

That’s really great, and I’m impressed that we’ll be able to ditch Function.prototype.bind() for cases like these. But what if we wanted dynamic this? There have been some proposals, such as thin arrow syntax, but some feel that the proposals add would add confusion with casual coders or that dynamic this isn’t important. On Kevin Smith’s survey of 20667 functions from a large number of code bases, Dr Axel Rauschmayer wrote the following:

These findings mean that JavaScript most urgently needs easy ways to define subroutines (with lexical this) and methods. ECMAScript.next therefore makes the right choices. Another implication is that arrow functions with dynamic this are not that important, even for current JavaScript code.

The confusion argument holds a lot of weight, I suppose. Like the difference between single quotes and double quotes in Perl/PHP/sh/etc, having fat arrows and thin arrows in JavaScript could cause the same confusion. However, in my experience, such confusion is usually cleared up in a very short period of time. We should be trying to improve the language for people who use JavaScript every day, rather than people who just write a couple of functions every 6 months to 2 years.

That being said, if there’s no call for it, then maybe it shouldn’t exist. I did think of one (albeit small) use case recently where dynamic this in arrow functions would shine: generic instance methods. You’d always want these to be lightweight (no [[Construct]] or prototype) and dynamic this. Take shims of native array generics introduced in ES5, for instance. You’d never get these to pass their respective tests on the test262 suite because all the existing shims have a prototype property and don’t throw an error when you try and construct them. With dynamic this, we could make ES6 shims of ES7 functions virtually indistinguishable ― Function.prototype.toString aside ― from their native counterparts and use the test262 suite to verify them. Like I said, it’s a small use case, but I think it would be nice to have.

Either way, I’m looking forward to being able to use arrow functions in JavaScript. As soon as the finalised specification draws near, I think we can expect minifiers to adopt support for this syntax and churn out backwards-compatible minified code.

 

JavaScript masked inputs, do we need them?

02 Nov

I recently learned that jQuery UI was to get its own input mask plugin.

jQuery UI input masks
jQuery UI’s upcoming masks

If you’re not sure what an input mask is, it’s where a defined set of rules govern what text can be input into a field. As you type, the text in the input mask may be altered to a specific format, like a telephone number or date, or text may be blocked completely, when entering a number where the rules specify a letter should be, for instance.

Thankfully, we don’t see much input masking on the web. Most web authors stick to validation and proper labelling to ensure their visitors enter values correctly. I suspect this is due to the difficulty involved in making masked inputs work well in a cross browser manner. The jQuery UI team must at least see a demand for input masks to be considering implementing them, but I’ve yet to see one in action on a large production website.

I chose the word ‘thankfully’ because I’ve never been a big fan of masked inputs. Aside from the cross-browser issues, you also have to deal with accessibility issues. Here’s a short list of some of the problems a developer will run into when creating a masked input:

  • Ranges are awkward to work with, and you’ll struggle to do this right without using them.
  • Messing around with the value of an input whilst the user is typing can (and will, in most cases) break the browser’s undo function.
  • If you’re masking the input with text, it’s hard to get it to look good, especially with a variable-width font.
  • Complex masks can be confusing for the user. For example, the British post code has several variations, messing around with the formatting whilst the user is typing could confuse them because what they typed doesn’t look like their post code.

Some examples I’ve seen try and mitigate these problems by using a different approach, like using multiple inputs and moving the focus from one to the next as the user is typing. These come with their own host of accessibility problems, like preventing copy/paste on the whole text.

My short journey to the dark side

I decided that, rather than just complain about current implementations of masked inputs, I’d see if I could come up with anything better. So, while the SO was watching the telly, I set about putting an idea into practice. And it was tough! You can see the fruits of my labour here:



[iframe http://jsfiddle.net/AndyE/hnJhY/show/light 100% 60px]

I know, it’s very basic. It looks and works best in IE, though that’s purely accidental. I ran into several annoying cross browser issues along the way and didn’t get much time to polish it up. As a proof-of-concept, though, I think it gets the point across. It works by overlaying a <span> element above the text field, and that element contains the mask text with each letter of text being wrapped in its own span element. This allowed me to vary the colour of the static / characters. pointer-events: none is used so that WebKit and Gecko allow you to click through the span to focus the input text. In IE, I cleverly — if I may say so myself — set contentEditable = 'true' on the <span> so that, when it is focussed, the caret position is obtained and seamlessly passed to the <input> at the correct position.

Despite its shortcomings, I’m rather pleased with the result. It allows undo to continue working in WebKit/Trident, and this functionality could be extended to Gecko, at least. However, there are several serious issues with the approach, the biggest being that text positioning in replaced elements is not the same as in non-replaced elements. In IE, the mask text and the input text are perfectly aligned. In most other browsers, the input text is a pixel or so off. Someone with more time on their hands may be able to come up with a way to feature detect this and adjust the input padding values accordingly.

If you’re thinking about using a masked input, I’d advise you to really weigh up whether it will really give you more than good validation and proper labelling your input fields. If you need guidelines for what your users should enter, the HTML5 placeholder attribute will serve you well enough, and there are plenty of shims to get the attribute working in unsupported browsers. If you decide to use a masked input anyway, then at least use a nice looking fixed width font.

 

ES6 – a quick look at Weak Maps

31 Oct

One of my favourite proposals in ECMAScript Harmony is Weak Maps. Simply put, ‘weak maps are unordered tables mapping objects to values’ with references to those objects and values being weak. A weak reference means that the item won’t be protected from garbage collection if no other references are held. For example:

// Using the proposed API (currently implemented in Firefox)
var wm = WeakMap();

(function () {
    var obj = {};
    wm.set(obj, 1);
})();

console.log(wm); //-> "[object WeakMap]"

By now a very obvious use case might have occurred to you, but I’ll get to that in a minute. When the above function finishes execution, obj is no longer reachable, so it can be garbage collected even though our WeakMap object is still reachable. This addition to the language is a useful tool for an age-old concern in JavaScript and the DOM; memory leaks. That aforementioned use case is becoming more obvious now, eh?

Where do Weak Maps fit in with current code?

OK, if you never had to implement this kind of thing before, you might not have thought of jQuery’s data() method. jQuery.data() allows us to attach an arbitrary value to a DOM object. Whilst you can do this with expando properties, ordinarily you run the risk of circular references and memory leaks. jQuery tackles this by creating a unique ID for itself (only once) and each element it is attaching data to. It tacks the element’s unique ID, which is really just an incremented counter, onto an expando property whose name is the unique ID. So it looks something like this:

     element[jQuery.expando] = elementId;

Any data you attach to the element is actually stored in an array at index elementId. jQuery is able to avoid memory leaks because there are no circular references, and it can delete all stored data when the page is unloaded (or the element is removed using jQuery’s own methods). However, it does have some limitations. For example — according to the source code — object/embed/applet cannot accept expando properties and, therefore, jQuery.data() cannot work with them.

Weak maps come in here because they can do the job much better. They cut out the need for the expando property entirely, along with the requirement of handling JS objects differently to DOM objects. They also expand on jQuery’s ability to allow garbage collection when DOM elements are removed by its own methods, by automatically allowing garbage collection when DOM elements no longer reachable after they’ve been removed by any method. Had WeakMaps been implemented in ECMAScript 3 (if only), jQuery’s workload with data() could have been significantly reduced. Perhaps jQuery wouldn’t have bothered implementing data if we could create weak maps, though.

Another use case to consider is secretly extending objects without the danger of naming collisions. Using someGloballyAvailableObject.someProperty = "some arbitrary value"; as an example, what if someGloballyAvailableObject already has someProperty? We’ve just written a potentially script-breaking piece of code. However, with a weak map we can eliminate this danger entirely:

(function () { 
    var wm = new WeakMap();
    wm.set(someGloballyAvailableObject, {someProperty:"some arbitrary value"});
})();

There’s also a hidden bonus here. I used the word secretly before because no other piece of our script can access this mapped value if we never expose the wm variable.

You might recall (if you read it) my article on creating lookup lists. If you do, you might be thinking that weak maps are a good use for creating lists, but in reality this isn’t the case because weak maps — in the current proposal, at least — will only map a value to an object.

Weak map compatibility shims

A true weak map is technically impossible in ECMAScript 3. We can create a map of objects to values by simply using two arrays:

function WeakMap() {
    this.keys = [/* key01, key02, key03 */];
    //                ↓      ↓      ↓
    this.vals = [/* val01, val02, val03 */];
}

Unfortunately, there’s 2 very important caveats here. Firstly, these references are not (and cannot be) weak, so they will not be garbage collected as long as the mapping exists. Secondly, for our get(key) method to work, we need to search our keys array. This significantly impacts performance, particularly on large maps.

As for ES5, I was pointed in the direction of this implementation recently. It’s very clever; It eliminates the need for a keys array and uses a custom valueOf function to keep track of the mapped value. I profiled the method in Chrome and it does indeed appear to prevent leaks. However, it does still have its limitations like not working on frozen objects or objects whose valueOf function is not configurable.

 
 

Update: HTML5 oninput event plugin for jQuery

24 Oct

About a year ago, I wrote my first special events plugin for jQuery — a cross-browser implementation of the HTML5 oninput event. A while afterwards, though, it became apparent that there were a multitude of issues with browsers that already implemented the event.

  • Opera 10.x doesn’t fire the event for cut, paste, undo & drop operations on <input> elements. They fixed this in Opera 11, though.
  • Safari 4.x and lower don’t support the event for <textarea> elements. The textInput event is supported on them for 3.1+, however.
  • Internet Explorer 9 forgets to fire the event when the backspace key is used to delete text. Other than that majorly horrendous oversight, they almost got it right.
  • Firefox has issues that make feature detection very difficult. In fact, detection is only possible via another Firefox proprietary feature, which I suppose is rather lucky.

With these problems stacking up, my code was stacking up too — how could I detect and work around each of these problems? On top of that, I couldn’t easily make the event work with delegate() or live(). Soon, it became apparent that I was going to have to completely rethink the approach I made in the original plugin.

Feature detection

The original code used feature detection to discover whether browsers supported the event. "oninput" in document.documentElement is enough for this in most browsers, but the aforementioned Firefox issues required an excellent little snippet from Daniel Friesen, which I slightly modified. It was a shame though, as this extra work bulked up the plugin a little more than I would have liked. Safari didn’t like our feature detection either, because even though our snippet told us the browser implemented support for the event, it doesn’t tell us that <textarea> won’t fire it.

I eventually decided that feature detection wasn’t going to work — graceful degradation, on the other hand, might. This involves binding to all known events that fire when an input element is modified, and then setting a flag to tell the event handlers whether or not they need to execute. For events that fire pre-DOM modification, we set a timer with timeout value of 0ms (this will be adjusted to browser’s minimum allowable value). The events that fire post-DOM modification cancel this timer. So, let’s say our browser is Internet Explorer 6, we have some text in our clipboard and we just pressed Ctrl+V in a <textarea> that has our events bound. For the Ctrl key, the onkeydown event sets the timer but when it executes the value hasn’t changed, so the handler does nothing. For the V key, the plugin will handle the events in the following sequence:

Pre-DOM modification
    onkeydown -> timer is set
    onpaste   -> previous timer is cleared, new timer is set

Post-DOM modification - DOM is modified, textarea's value is updated but element hasn't repainted yet
    onpropertychange -> timer is cleared, the handler is triggered

Opera 9, however, the best possible compatibility we can provide is via the onkeydown event, so that sets the timer which executes almost instantly, triggering our special event handler. In Safari 4, the textInput event fires post-DOM modification, so that clears the timer and triggers the handler, giving seamless `oninput` compatibility to the developer.

Late binding

No, not that kind of late binding. In order to mitigate the lack of event bubbling for our Internet Explorer polyfill, I opted to have the plugin not bind the input events to the element right away if it wasn’t an <input> or <textarea>. Instead, it binds several bubbling events — onfocusin, onmouseover and ondragstart — to the element. When one of those events fires, event.target.tagName is checked and if it is “INPUT” or “TEXTAREA” then we bind our input events to it. This allows delegate() to work really well in IE and I suspect, but haven’t verified, this is how jQuery is able to offer event delegation for non-propagating events such as onresize.

Problems with the new approach

Undoubtedly, the biggest problem is naming the special event. I can’t think of a way to have a special event named `input` that binds to the native `input` event and completely overrides it because, when we come to trigger the event later, we can’t. In my oh-so finite wisdom, I decided that the best solution I could provide was a differently named special event. So, when using the plugin now, you need to bind to "txtinput". $(selector).input(function () {}); will still work, though.

Another problem was teardown. Suppose we have a DOM structure like body -> div -> input — now, what happens if we bind to the <body> and <div> elements? Actually, this works completely as expected but, what if we unbind from one of those elements? Our teardown function needs to make sure that no other handlers are relying on our bound events before we remove them. The solution makes use of data and, every time an event is bound, increases an internal count to keep track. This counter is decreased for each of those elements in the teardown.

You can see the updated plugin at the original project page.

 

Building and checking lists in JavaScript

16 Sep

Recently, I was building a white-list of strings that I needed to check an input string against. It reminded me to write about something I wanted to write about for a while now.

First, lets take a look at the different ways we can define a list of strings:

Using arrays as lists

Normally, this is the first thing you would think of when building a list of strings. It might look something like this:

var list = [ "item1", "item2", "item3", "item4", "item5" ];

if (list.indexOf("item3") > -1) {
}

Fairly straightforward, right? Array lists are useful if you’re iterating over them and using each value for something, but when it comes to white-listing or black-listing something, it gets a little more complicated.

Advantages

  • Easy to define and maintain.
  • Can iterate over and perform a task on each item
  • Simple method to add values — list.push("item6");.
  • ES5 makes it easy to search for value existence — list.indexOf("item3"); //-> 2.

Disadvantages

  • Can be awkward to avoid adding duplicate values at runtime.
  • Non-ES5 implementations require a shim or a for loop to search for value existence.
  • The larger the array, the more performance significantly degrades.

Using a regular expression

I see this method used quite a lot, it’s a simple regular expression with all the words joined by the pipe symbol | for alternation:

var list = /^(?:item1|item2|item3|item4|item5)$/;

if (list.test("item1")) {
}

This is a decent method for small lists that are intended to be constant and never modified at runtime.

Advantages

  • More widely supported than Array.prototype.indexOf.
  • Modern regex implementations appear to be able to cope well with even large lists.
  • Case-insensitive searches are easier, just add the /i modifier.

Disadvantages

  • Regular expressions require further understanding than basic JavaScript, it’s easy for naive users to make a mistake (such as missing ^ and $).
  • Difficult to modify at runtime, creating a new regexp may require string escaping.
  • Less readable and maintainable when the list is large.
  • No best of both worlds, you can’t use the regex to iterate over and perform a function on each list item.

Using an object

This is my preferred method of defining a list, offering the most flexibility and the fastest lookup methods.

var t = true, list = {item1:t, item2:t, item3:t, item4:t, item5:t};

if ("item3" in list) {
}
if (list.hasOwnProperty("item3")) {
}
if (list.item3) { // "truthy" values only
}

I defined the list with true as the value for each item, but you could assign null or undefined if you want to use the in operator or hasOwnProperty.

Advantages

  • Easy to iterate over and do something with each item/property.
  • Custom values can be used for even more flexibility.
  • Very easy to add/remove items at run time, with no chance of duplicate items.
  • Code is easily readable, writeable and maintainable. Omitting string delimiters for property names makes for the same amount of typing as an Array (if assigning a single character variable/value).

Disadvantages

  • Lots of seemingly redundant code when not actually using values. It’s more typing than should be needed!
  • Potential naming collisions with Object.prototype properties if using the in operator or boolean checks.

Some slight changes to Object literal grammar would make this approach even more perfect. If we could just write { item1, item2, item3, item4, item5 } to have an object initialized with those properties (and undefined values) or { item1: item2: item3: item4: item5: true } to have 5 properties defined with the same value, our syndrome-less carpal tunnels would be thanking us in years to come. I know something like that has been proposed for ECMAScript Harmony, so let’s hope that works out.

Performance

Mostly for myself, I set up a JSperf test to compare the performance between the different lookup methods. Here’s what I learned:

  • Array.prototype.indexOf is, as expected, the slowest. If you’re using a shim for older browsers, expect this to be sickeningly slow.
  • The straight boolean tests are the fastest by a long way, but remember they’re not the strictest test.
  • Opera is able to optimize the regular expression so that it is faster than the in operator and hasOwnProperty.
  • Chrome’s hasOwnProperty function appears to be well optimized, since in all the other browsers, in was the faster of the two.
  • Firefox is pretty slow compared to the other browsers when it comes to boolean checks.

So, there you have it. Don’t use arrays for lists and lookups because Array.prototype.indexOf isn’t as fast as other methods you can use. In fact, if you’re bothered about speed at all, use one of the object methods. Some methods aren’t always appropriate, for instance if you want to assign custom values to your lists they might not always be truthy. You’re always safe with hasOwnProperty, but if you control where the values are coming from (e.g. list[element.tagName]) go with the truthy values for best performance.

 

Global `eval` with a result in Internet Explorer

24 Aug

A while ago, I was charged with the task of writing a JavaScript console window for certain environments that didn’t have access to the Internet Explorer developer tools. Such environments include Windows Desktop Gadgets and applications that make use of the .NET or COM WebBrowser controls, that run on the Internet Explorer engine (MSHTML).

The first non-trivial task was figuring out how to make Internet Explorer execute code in the global scope and then get the result. Indirect eval doesn’t help me because I need to support document modes where IE’s eval implementation is broken. It was clear that I would have to use Internet Explorer’s proprietary window.execScript function, but I wasn’t sure how I would get the result to display in the console window. Looking around the web didn’t help. As usual, kangax had an article and even a solution for providing a somewhat cross-browser global eval. However for Internet Explorer, the solution didn’t return a result so I was back to square one and it was time to get my hands dirty.

To begin with, I tried what was a rather naive attempt at a quick solution:

function executeConsoleInput(code) {
    var result;
    window.execScript("console.___lastInputResult___ = " + code);
    result = console.___lastInputResult___;
    delete console.___lastInputResult___;
    return result;
}

Before I tested it I already knew what the big problems would be:

  • All input becomes an expression, no statements or declarations allowed. This means any of var, try, catch... finally, if...else, do... while, etc will throw a syntax error. Also, function foo() { } is treated as a function expression and not a declaration.

  • Aside from that major spanner in the works, the first semi-colon in our code finalizes the assignment to executeConsoleInput.result, so anything after that is evaluated but not part of the result.


So this really wasn’t a viable option unless I wanted to limit the console user to single expressions. However, I felt I was on the right track and it didn’t take me long to realize I could use both execScript and eval together:

function executeConsoleInput(code) {
    var result;
    window.execScript("console.___lastInputResult___ = eval('" + code + "')");
    result = console.___lastInputResult___;
    delete console.___lastInputResult___;
    return result;
}

Perfect! …well, almost. Although this worked perfectly on a few short statements it quickly became clear I’d still been a little naive. Certain characters in the input would, quite obviously, break eval. Line-breaks were the most troublesome. Eventually, I came up with this and added it to the solution:

code = code.replace(/["'\\]/g, "\\$&").replace(/\r\n/g, "\\n");

After re-reading kangax’s article, I decided to post a comment with my solution for a global eval that returns a result, but since I’ve been working a little more on the console recently I decided to upgrade the comment to a fully fledged article of my own.

What’s even more intriguing about this is that it could be a viable polyfill for global eval in IE 8 and lower and it definitely is viable for IE 9/10 running in compatibility modes. Why can I make this assertion? I set up a jsperf test that compares the two functions and in IE 9 compatibility modes the withEval function is faster! I could only test IE 7 in a virtual machine, where withEval was between 15-25% slower. Whether or not this is an acceptable loss compared to the result and compatibility mode gains is up for debate. Personally, I prefer the same behaviour across browsers and, generally, thousands of execScript(eval()) operations per second is enough for anyone. I would be very interested in an explanation for the IE 9 eval optimization, either way.

Update: It turns out I didn’t need to escape the input — as John-David Dalton points out in the comments, you can assign the expression to a global variable and give that to eval instead of a string value. D’oh, I’m not sure why that didn’t occur to me! This also works around a problem with unicode escape sequences in the string that I hadn’t gotten around to addressing yet.

If we add this to kangax’s cross-browser globalEval code, we can make it behave to consistently return a value across Internet Explorer versions less than 9 and other browsers:

var globalEval = (function() {
  var isIndirectEvalGlobal = (function(original, Object) {
    try {
      // Does `Object` resolve to a local variable, or to a global, built-in `Object`,
      // reference to which we passed as a first argument?
      return window.eval('Object') === original;
    }
    catch(err) {
      // if indirect eval errors out (as allowed per ES3), then just bail out with `false`
      return false;
    }
  })(Object, 123);

  if (isIndirectEvalGlobal) {
    // if indirect eval executes code globally, use it
    return function(expression) {
      return window.eval(expression);
    };
  }
  else if ("execScript" in window) {
    // if `window.execScript` exists, use it along with `eval` to obtain a result
    return function(expression) {
      globalEval.___inputExpression___ = expression;
      window.execScript("globalEval.___lastInputResult___ = eval(globalEval.___inputExpression___)");
      return globalEval.___lastInputResult___;    
    };
  }

  // otherwise, globalEval is `undefined` since nothing is returned
})();

// and a simple test, inspired by kangax's detection method:
alert((function (Object) {
    return globalEval("Object === 123"); // result is false
})(123));

There is a slight difference in implementation requirements here, though – this requires globalEval to be defined as a global variable (or a property of the window object).

 

Creating a nice text shadow in Internet Explorer

20 May

I discovered a few days ago that Internet Explorer 9 didn’t include support for text-shadow. No surprises there, but I needed to put some white text on a greenish blueish background and it didn’t look that great. I stuck a text-shadow on it in Chrome, and it looked pretty good, so I set about looking for some sort of filter-based solution for Internet Explorer. I’m a firm believer of not using JavaScript when I don’t have to, so I limited my searching to CSS only. It didn’t take me long to find something; Zoltan’s CSS Blurred Text-Shadow in IE. His solution involves using :before, attr() and the blur filter. It also relies on using Paul Irish’s Conditional CSS Pattern, or using conditional comments to target IE with different stylesheets. It didn’t take me long to implement this solution because it was very easy.

<h1 data-innertext="Fear my shadow!">Fear my shadow!</h1>
h1 {
    color: #fff;
    font-family: Helvetica,Arial,sans-serif;
    font-weight: bold;
    font-size: 1.2em;
    text-shadow: #333 2px 2px 3px;
    padding-bottom: 2px; /* stops the "shadow" being chopped in IE */
}
.ie8n9 h1 {
    color: #333;
    zoom: 1;         /* required to give the element layout for filters */
    filter: progid:DXImageTransform.Microsoft.Blur(pixelradius=2);
}
.ie8n9 h1:before {
    color: #fff;
    content: attr(data-innertext);
    position: absolute;
}

This gave me a nice clean shadow in Internet Explorer 8 and 9 that matched Chrome’s text-shadow, differing only really in the same way Firefox 4′s shadows differ from Chrome’s. It’s possible to tweak the pixel radius, the colour and the element position to get an even closer match but please don’t waste too much time worrying that your shadows aren’t pixel-perfect in all browsers. Zoltan originally reported the trick to work with IE 8 and 9, but later discovered some issues that didn’t really apply to me — it looked much the same in IE 8/Vista and IE 9 in IE 8 mode on Win 7.

Zoltan asked at the end of his blog post if anyone could come up with a better solution. It was only after discovering and answering a related question on Stack Overflow (you know, where all my blogging inspiration comes from) that I realized you could just do what :before is doing behind the scenes anyway. So I changed my code to this:

<h1><span>Fear my shadow!</span><span>Fear my shadow!</span></h1>
h1 {
    color: white;
    font-family: Helvetica,Arial,sans-serif;
    font-weight: bold;
    font-size: 1.2em;
    text-shadow: #333 2px 2px 3px;
    padding-bottom:2px;
}
.shadow { display: none; }
.ielte9 > h1 > span {
    position: absolute;
    color: white;
}
.ielte9 > h1 > span.shadow { 
    display: inline-block;
    zoom: 1;
    color: #333;
    filter: progid:DXImageTransform.Microsoft.Blur(pixelradius=2);
}

So, for a little extra markup and targeting our CSS rules to IE 9 and lower, we get a working solution for IE 7-9. This also doesn’t suffer the same bug that Zoltan mentioned in his post, because that applies to :before. Furthermore, this solution will work in IE 6 if you remove the > direct descendant selectors. IE 6′s filters don’t look as good, though.

Shadow in Chrome

Google Chrome

Shadow in Firefox

Firefox 4

Shadow in IE 9

Internet Explorer 9

Shadow in IE 8

Internet Explorer 8

Shadow in IE 6

Internet Explorer 6

Unfortunately, my Vista/IE 7 machine has a busted HDD so I can’t test it right now, but I expect it would look similar to the IE 8 screenshot. The extra markup shouldn’t be a big deal, because you’re using text-shadow sparingly, right? …Right!? Of course, it’s not practical if you’re applying shadows to large paragraphs of text and it won’t do most things that text-shadow can do without, perhaps, a lot of tweaking, but if you just want to spice up your headings a little it just might do the job for you.

NB: I’m sure people have been using this technique for years, but I wasn’t able to find any posts that didn’t involve using JavaScript or using DropShadow/Glow filters directly on the text, which look absolutely awful.

 

Internet Explorer 9′s problematic console object

04 Apr

I sent out a quick tweet the other day after answering this question on Stack Overflow. Apparently, Internet Explorer 9 had caused the asker some confusion by not giving the console object permanent residency as part of the DOM – you have to open the developer tools for any tab you want the object to be made available to first. As an aside, the asker also wondered why when he tried to use console.log.apply, he got an error. After some quick investigations, it appeared obvious that the console object being injected into the window by the developer tools hadn’t received an update since Internet Explorer 8 and so the methods it contains aren’t instances of Function like all the most other DOM methods. The first thing that popped into my head was to try Function.prototype.bind.apply and see if it worked, although I wasn’t optimistic.

var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);

To my surprise, it worked great. I posted it as my answer and sent out the tweet to let the world know the crisis was over. Then, today a similar question was posted, again asking why console.log.apply doesn’t work. I had a little more time, so decided to rework the solution to apply to all the console methods that IE supports. Whilst writing the function, I discovered that IE still reports console methods as objects when using the typeof operator:

typeof console.log;
//-> "object"

This actually violates the ECMAScript 5th edition’s rules for the typeof operator, which specifies “function” should be returned for both native and host objects that implement [[Call]]. I headed over to Microsoft Connect to see if they were still accepting bug reports, but decided to search first and found that kangax had beaten me to it (he reported it pre beta and got a generic “we’re investigating” response). Instead, I 1-upped his bug report and added my workaround, which I’ll also post here in a slightly more concise form:

if (Function.prototype.bind && console && typeof console.log == "object") {
  [ 
    "log","info","warn","error","assert","dir","clear","profile","profileEnd" 
  ].forEach(function (method) {
    console[method] = this.call(console[method], console);
  }, Function.prototype.bind);
}

Now if we take another look at these methods, we should get (more or less) the same result in each browser:

typeof console.log;
//-> "function"
    
Object.prototype.toString.call(console.log);
//-> "[object Function]"

console.log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"

The usefulness of Function.prototype.bind here got me thinking — if we can make native copies of host objects, perhaps we can make native copies of ActiveX objects and methods too? nope.

Update

You can achieve the same result with IE 8′s console too, using a compatibility implementation of bind, but you must bind to Function.prototype.call, rather than console.log:

var log = Function.prototype.call.bind(console.log, console);
typeof log;
//-> "function"
 

Helpful error messages aren’t just a JavaScript’s throw away

17 Jan

This is one that’s been bugging me for years, but today something happened that finally made me decide to rant about it. ECMAScript’s throw statement has it’s uses in try... catch... finally blocks but it’s also used often outside, on its own, to halt script execution. The most notable example I can think of is on line 480 of Crockford’s json2.js:

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');

Now, most browsers don’t have a problem with this and not just because they support native JSON.parse. They will happily throw this exception and output the error message appropriately. Except for our old buddy, Internet Explorer. Internet Explorer does something amazingly stupid. It successfully throws an error, but the message accompanying it is “Exception thrown and not caught”. Wow, that’s so ridiculously unhelpful I could cry (but I promised myself I wouldn’t). I’m forced to hunt down the source of the error in my JavaScript code, something that was no easy task in IE 7 due to inaccurate reporting of line numbers and file names. You could argue that “JSON.parse” isn’t a very valuable error message either, but that’s beside the point.

The strange thing is that Internet Explorer will behave properly if the throw statement is throwing an Error object. The error message will be the one supplied to the Error constructor. So why doesn't this happen for Error's brethren; EvalError, TypeError, SyntaxError, RangeError, URIError and ReferenceError? Other browsers will display the error message even if you just throw a string.

When Internet Explorer 9 hit beta, I decided to report this as an "interoperability issue". The Internet Explorer team are always banging on about how they're trying to make Internet Explorer work like other browsers by following standards and non-standard, but popular, implementations of various functionality. I thought to myself, "How hard can it be to fix this?". Surely, there will be one code path for if you throw an Error object and another code path for everything else, so the first one could be quite easily expanded to accommodate everything else instead? As it happens, today my issue was changed to "Resolved", then "Closed" as "By design".

So there you have it, straight from the horse's mouth; Internet Explorer hinders your development in as many ways as possible "by design".

For some reason, the link to the bug report is telling people they don't have the required permissions to view. It is set to public, however, so I'm not sure what's going on there (perhaps they want to hide their shame!).