<?xml version="1.0"  encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="http://thingsinjars.com/includes/style/rss.css" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="http://thingsinjars.com/rss/js+css" rel="self" type="application/rss+xml" />
<title>Things in Jars</title>
<link>http://thingsinjars.com/</link>
<description>Articles from Things in Jars</description>
<language>en</language>
<docs>http://en.wikipedia.org/wiki/RSS_(file_format)</docs>
<lastBuildDate>Sat, 27 Apr 13 00:00:00 -0700</lastBuildDate>
<ttl>45</ttl><item>
<title>GhostStory</title>
<link>http://thingsinjars.com/post/474/ghoststory/</link>
<guid>http://thingsinjars.com/post/474/ghoststory/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-474">
        <p><a href="http://thingsinjars.com/post/474/ghoststory/">GhostStory</a></p>
<p>During all the research I did for my CSS testing talk, I couldn't help but spot another gap where a testing tool could be useful. </p>

<h2>Cucumber</h2>

<p>Cucumber is a technology used widely in automated testing setups, mostly for acceptance testing - ensuring that the thing everybody agreed on at the beginning was the thing delivered at the end. </p>

<p>This is accomplished by having a set of plain text files containing descriptions of different scenarios or aspects of the application, usually with a description of the actions performed by an imaginary user. You describe the situation (known as a 'Given' step), describe the user's action ('When') and describe the expected outcome ('Then').</p>

<p>The language (properly known as gherkin) used in these files is deliberately simple and jargon-free so that all the key stakeholders in the project - designers, developers, product owners - can understand but the files are also written in a predictable and structured style so that they can, behind the scenes, be turned into testable code. </p>

<p>What occurred to me when looking into this area was that there wasn't an agreed terminology for specifying the layout/colour/look and feel of a project in plain text. Surely this would be the perfect place to drop in some cucumber salad. </p>

<p>What we've got now is a project based on SpookyJS - a way of controlling CasperJS (and, therefore PhantomJS) from NodeJS - which contains the GhostStory testing steps and their corresponding 'behind the scenes' test code. There are only two steps at the moment but they are the most fundamental which can be used to build up future steps. </p>

<p><p>By the way, the name 'GhostStory' only just won out over the original 'CucumberNodeSpookyCasperPhantomJS'. It kinda makes sense because it's built using a lot of ghost-named technologies (Spooky, Casper, Phantom) and cucumber test files are sometimes called "Story" files because they describe a user story.</p></p>

<h2>Implemented Steps</h2>

<p>Here, "Element descriptor" is a non-dev-readable description of the element you want to test - "Main title", "Left-hand navigation", "Hero area call-to-action". In the project, you keep a mapping file, <code>selectors.json</code>, which translates between these descriptions and the CSS selector used to identify the element in tests.</p>

<pre><code>Then the "Element descriptor" should have "property" of "value"
</code></pre>

<p>This is using the computed styles on an element and checking to see if they are what you expect them to be. I talked about something similar to this before <a href="http://thingsinjars.com/post/437/css-verification-testing/">in an earlier post</a>. This is related to the <a href="http://csste.st/techniques/frozen-dom.html">'Frozen DOM' approach</a> that my first attempt at a CSS testing tool, <a href="http://thingsinjars.com/post/438/cssert--like-assert-but-with-css-at-the-front/">cssert</a>, uses but this way does not actually involve a DOM snapshot.</p>

<pre><code>Then the "Element descriptor" should look the same as before
</code></pre>

<p>This uses the <a href="http://csste.st/techniques/image-diff.html">'Image Diff' approach</a>. You specify an element and render the browser output of that element to an image. The next time you run the test, you do the same and check to see if the two images differ. As mentioned many times before, this technique is 'content-fragile' but can be useful for a specific subset of tests or when you have mocked content. It can also be particularly useful if you have a <a href="https://speakerdeck.com/hagenburger/style-guide-driven-development">'living styleguide'</a> as described by <a href="https://twitter.com/Hagenburger/">Nico Hagenburger</a>. I've got some ideas about CSS testing on living styleguides that I'll need to write up in a later post.</p>

<h2>Future Steps</h2>

<p>Off the top of my head, there are a couple of other generic steps that I think would be useful in this project.</p>

<pre><code>Then the "Element descriptor" should have a "property" of "value1", "value2", ..., or "valueN"
</code></pre>

<p>This variation on the computed style measurement allows an arbitrary-length list of values. As long as the element being tested matches at least one of the rules, the step counts as a pass. This could be used to ensure that all text on a site is one of a certain number of font-sizes or that all links are from the predefined colour palette.</p>

<pre><code>Then the "Element descriptor" should look the same across different browsers.
</code></pre>

<p>This would build on the existing image diff step but include multiple browser runners. Just now, the image diffs are performed using <a href="https://github.com/Huddle/PhantomCSS">PhantomCSS</a> which is built on top of PhantomJS which is Webkit-based. This would ideally integrate a Gecko renderer or a Trident renderer process so that the images generated from one could be checked against another. I still feel that image diff testing is extremely fragile and doesn't cover the majority of what CSS testing needs to do but it can be a useful additional check.</p>

<h2>The aim</h2>

<p>I'm hoping this can sit alongside the other testing tools gathering on <a href="http://csste.st/">csste.st</a> where it can help people get a head-start on their CSS testing practices. What I'm particularly keen on with the GhostStory project is that it can pull in other tools and abstract them into testing steps. That way, we can take advantage of the best tools out there and stuff it into easily digested Cucumber sandwiches.</p>

<h2>Try it</h2>

<p>The GhostStory project is, naturally, <a href="https://github.com/thingsinjars/GhostStory">available on GitHub</a>. More usefully, however, I've been working on a fork of SpookyJS that integrates GhostStory into an immediately usable tool.</p>

<p>Please <a href="https://github.com/thingsinjars/SpookyJS">check out this project</a> and let me know what you think. I might rename it to distinguish it from the original SpookyJS if I can figure out exactly how to do that and maintain upstream relationships on GitHub.</p>
      </div>
]]></description>
<pubDate>Sun, 30 Dec 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>jHERE playground</title>
<link>http://thingsinjars.com/post/471/jhere-playground/</link>
<guid>http://thingsinjars.com/post/471/jhere-playground/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-471">
        <p><a href="http://thingsinjars.com/post/471/jhere-playground/">jHERE playground</a></p>
<p>Every couple of months, we have a Research Week. It's kind of like the well-known <a href="http://googleblog.blogspot.de/2006/05/googles-20-percent-time-in-action.html">Google 20% time</a> but instead of doing it one day a week, we gather up our time and do a week of maps-based hacking. It's totally cross-discipline so we usually gather a couple of developers, a couple of UX and visual designers, a QA and build something cool. In past Research Weeks, I've built or helped build the <a href="http://here.com/alien">Alien Easter Egg</a>, <a href="http://conversations.nokia.com/2012/11/09/groupon-weather-and-more-on-maps-nokia-com/">Maps Labs</a> and <a href="http://covermap.me">CoverMap.Me</a>. I also built a maps-based JSBin fork called JotApp.</p>

<p>When my partner-in-crime <a href="http://marcon.me/">Max</a> started working on the latest version of his <a href="http://jhere.net">jQuery plugin</a> (formerly called jOvi, now called jHERE), I wanted to build a new playground where people could play and build their own maps mashups and hacks really easily. My first thought was to rework the fork of <a href="http://jsbin.com">JSBin</a> again and maybe add in a slightly nicer default theme. I wanted users to be able to save to Gists so, seeing as there is already an SQLite and a MySQL adapter, I wrote a Gist adapter which appeared to the application as if it were a database but actually saved to anonymous Gists. The problem was that it was a bit too… heavy.</p>

<p>Don't get me wrong, JSBin is a fantastic project. It just does a lot more than I needed. I didn't need the MySQL adapter, the alternate themes, the localstorage or the user registration. Also, it's a bit too weighty for my phone. When someone tweets a link to a JSBin or a JSFiddle, I usually check it out on my phone and it's not the best experience. Seeing as HERE maps work on mobile, I wanted my playground to work, too. Rather than spend a couple of hours cutting out all the bits I didn't want from JSBin, I decided to spend a couple of hours building my own version from scratch. So, this past Sunday afternoon, that's exactly what I did:</p>

<p><a href="http://bin.jhere.net">jHERE Playground</a></p>

<p><a href="http://bin.jhere.net"><img src="http://thingsinjars.com/uploaded/images/expanded/jHERE-Playground.png" alt="jHERE Playground on Mobile" /></a></p>

<p>It's written in NodeJS on top of express and works nicely on desktop, iPad and mobile.</p>

<p>The project is open-sourced on <a href="https://github.com/thingsinjars/map-playground">GitHub</a> (naturally) and can be modified to be a general JS-playground for anything. If you fancy a simple, self-hosted JS hackspace, just change the default HTML, CSS and JS and it's ready to go.</p>
      </div>
]]></description>
<pubDate>Tue, 13 Nov 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Some App.net recipes</title>
<link>http://thingsinjars.com/post/469/some-appnet-recipes/</link>
<guid>http://thingsinjars.com/post/469/some-appnet-recipes/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-469">
        <p><a href="http://thingsinjars.com/post/469/some-appnet-recipes/">Some App.net recipes</a></p>
<p>This is a collection of code snippets for various common tasks you might need to accomplish with the <a href="https://github.com/appdotnet/api-spec">App.net API</a>. Most of these are focused on creating or reading geo-tagged posts. They require a developer account on app.net and at least one of an App ID, App Code, App Access Token or User Access Token. The calls here are implemented using jQuery but that's just to make it easier to copy-paste into the console to test them out (so long as you fill in the blanks). </p>

<p>An important thing to bear in mind is the possibility for confusion between a 'stream' and 'streams'. By default, a 'stream' is a discrete chunk of the 20 latest posts served at a number of endpoints. This is the open, public, <a href="https://alpha-api.app.net/stream/0/posts/stream/global">global stream</a>:</p>

<pre><code>https://alpha-api.app.net/stream/0/posts/stream/global
</code></pre>

<p>On the other hand, 'streams' are long-poll connections that serve up any matching posts as soon as they are created. The connection stays open while there is something there to receive the response. Streams are available under:</p>

<pre><code>https://alpha-api.app.net/stream/0/streams
</code></pre>

<p>Totally not confusing. Not at all.</p>



<h2>Creating a user access token</h2>

<p>Required for any user-specific data retrieval. The only tricky thing you'll need to think about here is the <code>scope</code> you require.</p>

<pre><code>scope=stream email write_post follow messages export
</code></pre>

<p>should cover most requirements.</p>

<h3>Requires</h3>

<ul>
<li><code>client_id</code></li>
</ul>

<p>Visit this URL:</p>

<pre><code>https://alpha.app.net/oauth/authenticate
    ?client_id=[your client ID]
    &amp;response_type=token
    &amp;redirect_uri=http://localhost/
    &amp;scope=stream email write_post follow messages export
</code></pre>



<h2>Using a user access token to create a post (with annotations)</h2>

<h3>Requires</h3>

<ul>
<li><code>User Access Token</code></li>
<li>text to post</li>
</ul>

<p>The text is essential if you don't mark a post as '<code>machine_only</code>'. The annotations here are optional. Annotations don't appear in the global stream unless the requesting client asks for them.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({
    "annotations": [{
      "type": "net.app.core.geolocation",
      "value": {
        "latitude": 52.5,
        "longitude": 13.3,
        "altitude": 0,
        "horizontal_accuracy": 100,
        "vertical_accuracy": 100
      }
    }],
    "text": "Don't mind me, just checking something out."
  }),
  dataType: 'json',
  success: function(data) {
    console.log("Text+annotation message posted");
  },
  error: function() {
    console.log("Text+annotation message failed");
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/posts?access_token={USER_ACCESS_TOKEN}'
});
</code></pre>



<h2>Using a user access token to post a machine_only post (with annotations)</h2>

<h3>Requires</h3>

<ul>
<li><code>User Access Token</code></li>
</ul>

<p>In this example, we're creating a post that won't show up in user's timelines and adding the 'well-known annotation' for geolocation.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({
    "annotations": [{
      "type": "net.app.core.geolocation",
      "value": {
        "latitude": 52.5,
        "longitude": 13.3,
        "altitude": 0,
        "horizontal_accuracy": 100,
        "vertical_accuracy": 100
      }
    }],
    machine_only: true
  }),
  dataType: 'json',
  success: function(data) {
    console.log("Non-text message posted");
  },
  error: function() {
    console.log("Non-text message failed");
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/posts?access_token={USER_ACCESS_TOKEN}'
});
</code></pre>



<h2>Retrieve the global stream, including geo-annotated posts if there are any</h2>

<h3>Requires</h3>

<ul>
<li><code>User Access Token</code></li>
</ul>

<p>This is a very basic call to retrieve the <a href="https://alpha-api.app.net/stream/0/posts/stream/global">global stream</a> but it also instructs the endpoint to return us all annotations and include machine-only posts.</p>

<pre><code>var data = {
  "include_machine": 1,
  "include_annotations": 1,
  "access_token": "{USER_ACCESS_TOKEN}"
};

$.ajax({
    contentType: 'application/json',
    dataType: 'json',
    success: function(data) {
      console.log(data);
    },
    error: function(error, data) {
      console.log(error, data);
    },
    type: 'GET',
    url: 'https://alpha-api.app.net/stream/0/posts/stream/global',
    data: data
});
</code></pre>



<h2>Creating an App Access Token</h2>

<p>This is necessary for many of the <code>streams</code> operations. It is not used for individual user actions, only for application-wide actions. </p>

<ul>
<li><a href="https://github.com/appdotnet/api-spec/blob/master/auth.md#app-access-token-flow">App.net API wiki on App Access Tokens</a></li>
</ul>

<h3>Requires</h3>

<ul>
<li><code>client_id</code></li>
<li><code>client_secret</code></li>
</ul>

<p><code>client_credentials</code> is one of the four types of <code>grant_type</code> specified in the <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-31">OAuth 2.0 specification</a>. I had difficulty getting this to work when using a data object:</p>

<pre><code>var data = {
    "client_id": "{CLIENT_ID}",
    "client_secret":"{CLIENT_SECRET}",
    "grant_type": "client_credentials"
};
</code></pre>

<p>The <code>client_credentials</code> kept throwing an error. Instead, sending this as a string worked fine:</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: 'client_id={CLIENT_ID}&amp;client_secret={CLIENT_SECRET}&amp;grant_type=client_credentials',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, data) {
    console.log(error, data);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha.app.net/oauth/access_token'
});
</code></pre>

<p>One other thing to note is that this bit should be done server-side. This will throw a bunch of "…not allowed by Access-Control-Allow-Origin…" errors if you do it via jQuery.</p>

<h3>Returns</h3>

<pre><code>{
    "access_token": "{APP_ACCESS_TOKEN}"
    }
</code></pre>



<h2>Creating a <code>streams</code> format</h2>

<p>Now you have your app access token, you can use it to tell the service what kind of data you want back. The streams offered in the API have two quite powerful aspects. Firstly, filters allow you to run many kinds of queries on the data before it is streamed to you so you don't need to recieve and process it all. Secondly, the decoupling of filters from streams means you can specify the data structure and requirements you want once then just access that custom endpoint to get the data you want back any time.</p>

<h3>Requires</h3>

<ul>
<li><code>App access token</code></li>
</ul>

<p>This first example just creates an unfiltered stream endpoint</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({"object_types": ["post"], "type": "long_poll", "id": "1"}),
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, responseText, response) {
    console.log(error, responseText, response);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/streams?access_token={APP_ACCESS_TOKEN}'
});
</code></pre>

<h3>Returns</h3>

<pre><code>{
    "data": {
        "endpoint": "https://stream-channel.app.net/channel/1/{LONG_RANDOM_ENDPOINT_URL}",
        "id": "77",
        "object_types": [
            "post"
        ],
        "type": "long_poll"
    },
    "meta": {
        "code": 200
    }
}
</code></pre>



<h2>Using Filters to create a stream of geotagged posts</h2>

<p>We'll specify some requirements for our filter now so that it only returns back a subset of posts. The rules we're specfying here are:</p>

<pre><code>At least one item in the "/data/annotations/*/type" field
must "match"
the value "net.app.core.geolocation"
</code></pre>

<h3>Requires</h3>

<ul>
<li><code>User access token</code></li>
</ul>

<p>The <code>field</code> is specified in '<a href="http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer-02">JSON Pointer</a>' format. Within the response, there is a 'data' object and a 'meta' object. The data contains an 'annotations' object which contains an array of annotations, each of which has a type. This is represented as <code>/data/annotations/*/type</code>.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({"match_policy": "include_any", "clauses": [{"object_type": "post", "operator": "matches", "value": "net.app.core.geolocation", "field": "/data/annotations/*/type"}], "name": "Geotagged posts"}),
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, responseText, response) {
    console.log(error, responseText, response);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/filters?access_token={USER_ACCESS_TOKEN}'
});
</code></pre>

<h3>Returns</h3>

<p>The filter rules you just specified, the <code>id</code> of the filter (remember that for later) and the details of the application used to make the request.</p>

<pre><code>{
"clauses": [
    {
        "field": "/data/annotations/*/type",
        "object_type": "post",
        "operator": "matches",
        "value": "net.app.core.geolocation"
    }
],
"id": "527",
"match_policy": "include_any",
"name": "Geotagged posts",
"owner": {
    "avatar_image": {
        "height": 200,
        "url": "https://d2rfichhc2fb9n.cloudfront.net/image/4/Pr63PjEwJ1fr5Q4KeL3392BMgSnIAYlHxv8OkWwzx75V8quNfpaFp4VPpKnDRxdXtYYPtIutrDVdU9NbJn7hKApQL84T5sfB1D9bWTgtizMWInignv0WyPPfM2DpqSThQgvkB68vbPzjZ8VeKM02M2GySZ4",
        "width": 200
    },
    "canonical_url": "https://alpha.app.net/thingsinjars",
    "counts": {
        "followers": 30,
        "following": 65,
        "posts": 96,
        "stars": 0
    },
    "cover_image": {
        "height": 230,
        "url": "https://d2rfichhc2fb9n.cloudfront.net/image/4/UWZ6k9xD8_8LzEVUi_Uz6C-Vn-I8uPGEBtKb9jSVoFNijTwyEm1mJYpWq6JvnA6Jd4gzW76vFnbSWvM3jadhc1QxUl9qS4NTKiv3gJmr1zY_UpFWvX3qhOIyKrBPZckf2MrinqWay3H0h9rfqY0Gp9-liEg",
        "width": 960
    },
    "created_at": "2012-08-12T17:23:44Z",
    "description": {
        "entities": {
            "hashtags": [],
            "links": [],
            "mentions": []
        },
        "html": "&lt;span itemscope="https://app.net/schemas/Post"&gt;Nokia Maps Technologies Evangelist; CreativeJS team member; the tech side of museum140; builder of The Elementals; misuser of semi-colons;rn&lt;/span&gt;",
        "text": "Nokia Maps Technologies Evangelist; CreativeJS team member; the tech side of museum140; builder of The Elementals; misuser of semi-colons;rn"
    },
    "id": "3191",
    "locale": "en_GB",
    "name": "Simon Madine",
    "timezone": "Europe/Berlin",
    "type": "human",
    "username": "thingsinjars"
}
}
</code></pre>



<h2>Listening to the geotagged post stream</h2>

<p>This wil return a link to a long-lasting connection to the app.net stream that will only return posts with the geolocation annotation.</p>

<h3>Requires</h3>

<ul>
<li><code>filter_id</code> from the previous call</li>
</ul>

<p>Note: the <code>filter_id</code> was returned as <code>id</code> in the previous response.</p>

<pre><code>$.ajax({
  contentType: 'application/json',
  data: JSON.stringify({"object_types": ["post"], "type": "long_poll", "filter_id": "527"}),
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(error, responseText, response) {
    console.log(error, responseText, response);
  },
  processData: false,
  type: 'POST',
  url: 'https://alpha-api.app.net/stream/0/streams?access_token={APP_ACCESS_TOKEN}'
});
</code></pre>

<h3>Returns</h3>

<p>The same kind of response as the 'Creating a <code>streams</code> format' example except the data coming down on the stream is filtered.</p>

<pre><code>https://stream-channel.app.net/channel/1/{LONG_RANDOM_ENDPOINT_URL}
</code></pre>

<p>Open that URL up in your browser (seeing as we're testing) and, in a different tab, create a geo-tagged machine-only post (see above). Your post will appear almost instantly after you've submitted it.</p>
      </div>
]]></description>
<pubDate>Mon, 29 Oct 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Location-based time</title>
<link>http://thingsinjars.com/post/468/location-based-time/</link>
<guid>http://thingsinjars.com/post/468/location-based-time/</guid>
<description><![CDATA[
        <div class="teaser markdown" id="teaser-468">
        <p><a href="http://thingsinjars.com/post/468/location-based-time/">Location-based time</a></p>
<p>Inspired by the simplicity of <a href="http://thingsinjars.com/post/466/building-a-proximity-search/">implementing a proximity search using MongoDB</a>, I found myself keen to try out another technology.</p>

<p>It just so happened that I was presented with a fun little problem the other day. Given a latitude and longitude, how do I <strong>quickly</strong> determine what the time is? Continuing the recent trend, I wanted to solve this problem with Node.JS.</p>

<p>Unsurprisingly, there's a lot of information out there about timezones. Whenever I've worked with timezones in the past, I've always gotten a little bit lost so this time, I decided to actually read a bit and find out what was supposed to happen. In essence, if you're doing this sort of task. you do not want to have to figure out the actual time yourself. Nope. It's quite similar to one of my top web dev rules:</p>


  <p>Never host your own video.</p>


<p><strong>(Really, never deal with video yourself. Pay someone else to host it, transcode it and serve it up. It'll will always work out cheaper.)</strong></p>

<p>What you want to do when working with timezones is tie into someone else's database. There are just too many rules around international boundaries, summer time, leap years, leap seconds, countries that have jumped over the international date line (more than once!), islands whose timezone is 30 minutes off the adjacent ones...</p>

<p>To solve this problem, it needs to be split into two: the first part is to determine which timezone the coordinate is in, the second is the harder problem of figuring out what time it is in that timezone. Fortunately, there are other people who are already doing this. Buried near the back of the bottom drawer in very operating system is some version of the <code>tz database</code>. You can spend hours <a href="http://en.wikipedia.org/wiki/Tz_database">reading up about it</a>, its controversies and history on Wikipedia if you like. More relevantly, however, is what it can do for us in this case. Given an IANA timezone name – "America/New_York", "Asia/Tokyo" – you can retrieve the current time from the system's <code>tz database</code>. I don't know how it works. I don't need to know. It works.</p>

<h2>Node</h2>

<p>Even better for reaching a solution to this problem, <a href="https://npmjs.org/package/zoneinfo">there's a node module</a> that will abstract the problem of loading and querying the database. If you use the <code>zoneinfo</code> module, you can create a new timezone-aware Date object, pass the timezone name to it and <strong>it</strong> will do the hard work. awsm. The module wasn't perfect, however. It loaded the system database synchronously using <code>fs.readFileSync</code> which is I/O blocking and therefore a <em>Bad Thing</em>. Boo.</p>

<p>10 minutes later and <a href="http://marcon.me/">Max</a> had wrangled it into using the asynchronous, non-blocking <code>fs.ReadFile</code>. Hooray!</p>

<p>Now all I needed to do was figure out how to do the first half of the problem: map a coordinate to a timezone name.</p>

<h2>Nearest-Neighbour vs Point-in-Polygon</h2>

<p>There are probably more ways to solve this problem but these were the two routes that jumped to mind. The tricky thing is that the latitude and longitude provided could be arbitrarily accurate. A simple lookup table just wouldn't work. Of course, the core of the problem was that we needed to figure out the answer fast.</p>

<h3>Nearest Neighbour</h3>

<ol>
<li>Create a data file containing a spread of points across the globe, determine (using any slow solution) the timezone at that point.</li>
<li>Load the data into an easily searchable in-memory data-structure (such as a <a href="http://en.wikipedia.org/wiki/K-d_tree">k-d tree</a>)</li>
<li>Given a coordinate, find the nearest existing data point and return its value.</li>
</ol>

<h3>Point in Polygon</h3>

<ol>
<li>Create a data file specifying the geometry of all timezones.</li>
<li>Given a coordinate, loop over each polygon and determine whether this coordinate is positioned inside or outside the polygon.</li>
<li>Return the first containing polygon</li>
</ol>

<p>This second algorithm could be improved by using a coarse binary search to quickly reduce the number of possible polygons that contain this point before step 2.</p>

<p>Despite some kind of qualification in mathematic-y computer-y stuff, algorithm analysis isn't my strong point. To be fair, I spent the first three years of my degree trying to get a record deal and the fourth trying to be a stand-up comedian so we may have covered complexity analysis at some point and I just didn't notice. What I do know, however, is that k-d trees are fast for searching. Super fast. They can be a bit slower to create initially but the point to bear in mind is that you only load it once while you search for data lots. On the other hand, while it's a quick task to load the geometry of a small number of polygons into memory, determining which polygon a given point is in can be slow, particularly if the polygons are complex.</p>

<p>Given this vague intuition, I settled on the first option. </p>

<p>If I wanted to create a spread of coordinates and their known timezones from scratch, it might have been an annoyingly slow process but, the Internet being what it is, someone already did the hard work. <a href="https://gist.github.com/1769458">This gist</a> contains the latitude and longitude for every city in the world and what IANA timezone it is in. Score! A quick regex later and it looks like this:</p>

<pre><code>module.exports = [
  {"latitude": 42.50729, "longitude": 1.53414, "timezone": "Europe/Andorra"},
  {"latitude": 42.50779, "longitude": 1.52109, "timezone": "Europe/Andorra"},
  {"latitude": 25.56473, "longitude": 55.55517, "timezone": "Asia/Dubai"},
  {"latitude": 25.78953, "longitude": 55.9432, "timezone": "Asia/Dubai"},
  {"latitude": 25.33132, "longitude": 56.34199, "timezone": "Asia/Dubai"},
  etc…
</code></pre>

<p>(<a href="https://github.com/thingsinjars/coordinate-tz/blob/master/city_timezones.js">See the original on GitHub</a>)</p>

<p>All that's left is to load that into a k-d tree and we've got a fully-searchable, fast nearest neighbour lookup.</p>

<h2>Source</h2>

<p>The source for this node module is, of course, <a href="https://github.com/thingsinjars/coordinate-tz">available on GitHub</a> and the module itself is available for <a href="https://npmjs.org/package/coordinate-tz">install via npm</a> using:</p>

<pre><code>npm install coordinate-tz
</code></pre>

<p>When combined with the <a href="https://npmjs.org/package/zoneinfo"><code>zoneinfo</code> module </a> (or, even better, <a href="https://github.com/mmarcon/node-zoneinfo">this async fork of the module</a>), you can get a fast, accurate current time lookup for any latitude and longitude.</p>

<p>Not a bad little challenge for a Monday evening.</p>
      </div>
]]></description>
<pubDate>Mon, 15 Oct 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Using CSS :target to control state</title>
<link>http://thingsinjars.com/post/462/using-css-target-to-control-state/</link>
<guid>http://thingsinjars.com/post/462/using-css-target-to-control-state/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-462">
        <p><a href="http://thingsinjars.com/post/462/using-css-target-to-control-state/">Using CSS :target to control state</a></p>
<p>There can be a fair amount of discussion provoked by the phrase "CSS only" or "Built entirely in HTML and CSS" when it comes to tech demos. The discussion generally revolves around the fact that what the phrase actually means 99% of the time is "Using CSS for the graphical bits but tracking the mouse using JS" or "Using CSS transforms for most of it but using JS to calculate the values" or any number of variations on that theme. </p>

<p>Now, I'm not saying that's a bad thing at all, I quite happily called <a href="http://thelab.thingsinjars.com/CSSKart/">my interpretation of Super Mario Kart</a> CSS-only even though without JS, Yoshi wouldn't make it to the first bend. What these demos are doing, essentially, is using CSS as the rendering layer where previously, JS would have been used. By doing so, you even get some nice hardware acceleration thrown in. Not too bad.</p>

<h2>Why fall back?</h2>
<p>The reason we fall back to JS for a lot of things is because CSS is a declarative language (see my <a href="http://thingsinjars.com/post/437/css-verification-testing/">post on CSS testing</a> to learn more). However you say things should be is how they are. In CSS, you can't set a variable to one value, do something with it then set it to a different value and do something else. For a start, you don't have variables. Even if you did, the style sheet is read top-to-bottom before anything is done with it. The variable would always have the final value assigned to it, even the first time you used it. I'm simplifying a bit but not much. If you want to do anything clever, you generally need to resort to JS, an interpreted language.</p>

<h2>Really CSS only</h2>
<p>If you want to make something properly interactive but entirely CSS, you have to find a way to modify the state of the DOM so that different sets of styles can be applied to the same sets of elements. We actually do this all the time when we change the colour of a link on :hover. The user interacts with the page, the state of the page is changed slightly, a different style applies. There's a lot you can do now that you have a way to modify the page based on user interaction. Hooray for pseudo-classes! </p>

<p>An extremely important addition to the set of pseudo-classes available in CSS3 is the :target class. This becomes set on an element when the element is the target of a clicked link. Think of in-page jump links. When you click on one and the URL changes to 'blah.html#the-thing-you-clicked', the element with <code>id="the-thing-you-clicked"</code> gets the :target pseudo-class. Now you can affect it and its children with new styles. Now it becomes interesting, you can click on something on one bit of the page and it cause something to happen on another bit of the page. </p>

<h2>Multiple-nested states</h2>
<p>By nesting several elements around the thing you're intending to modify, you can now create a set of states entirely controlled by CSS. For example, with this HTML:</p>

<pre lang="html"><code>&lt;div id=&quot;red&quot;&gt;
  &lt;div id=&quot;blue&quot;&gt;
    &lt;div id=&quot;green&quot;&gt;
      &lt;div id=&quot;yellow&quot;&gt;
          &lt;p&gt;Hello.&lt;/p&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;#red&quot;&gt;Red&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#blue&quot;&gt;Blue&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#green&quot;&gt;Green&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#yellow&quot;&gt;Yellow&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#default&quot;&gt;Default&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
And this CSS:
<pre lang="css"><code>p {
    color:black;
}
#red:target p {
    color:red;
}
#blue:target p {
    color:blue;
}
#green:target p {
    color:green;
}
#yellow:target p {
    color:yellow;
}</code></pre>

<p>You can change the colour of the text by clicking on the link. Without any JS.</p>

<p><a href="http://jsfiddle.net/DMNSn/">See this on JSFiddle</a>.</p>

<h2>Shiny demos</h2>
<p>This still isn't perfect. There are still going to be many things that JS is best for, calculations being one, keyboard input being another. To try and find the best way to show this off, I tried to update CSS Mario Kart to be entirely CSS and I almost got there but wasn't 100% successful.</p>
<ul>
<li><a href="http://thelab.thingsinjars.com/CSSKart/cssonly.html">CSS-only Mario Kart</a></li>
</ul>

<p>I then started to build a zoetrope in CSS, found <a href="http://andrew-hoyer.com/experiments/zoetrope/">someone else</a> had already done it and decided to modify it.</p>

<ul>
<li><a href="http://thelab.thingsinjars.com/zoetrope/index.html#spin">CSS-only Zoetrope</a></li>
</ul>

<p>Maybe soon, the phrase "CSS only" will really mean "CSS only. And a bit of HTML."</p>      </div>
]]></description>
<pubDate>Sun, 15 Jul 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>CSSSquircle</title>
<link>http://thingsinjars.com/post/460/csssquircle/</link>
<guid>http://thingsinjars.com/post/460/csssquircle/</guid>
<description><![CDATA[
        <div class="teaser " id="teaser-460">
        <p><a href="http://thingsinjars.com/post/460/csssquircle/">CSSSquircle</a></p>
After a light-hearted challenge in work, I started trying to replicate a <a href="http://en.wikipedia.org/wiki/Squircle">Squircle</a> in CSS. This is a bit tricky as it can't be created using simple border-radius.

Fortunately, somebody else already did the hard work. There's a <a href="https://github.com/rdougan/nokia-meego-squircle-css">project on GitHub</a> by Robert Dougan which contains a fairly accurate squircle (good enough for screen, anyway). I decided to reproduce it reducing the number of elements used.

Here it is using pseudo-elements on a paragraph and a link tag.

<ul>
<li><a href="http://thelab.thingsinjars.com/cssquircle/">CSSSquircle</a></li>
</ul>

Now to convince the designers at <a href="http://maps.nokia.com/">work</a> to use it.      </div>
]]></description>
<pubDate>Tue, 12 Jun 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Sounds like a Hackathon</title>
<link>http://thingsinjars.com/post/459/sounds-like-a-hackathon/</link>
<guid>http://thingsinjars.com/post/459/sounds-like-a-hackathon/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-459">
        <p><a href="http://thingsinjars.com/post/459/sounds-like-a-hackathon/">Sounds like a Hackathon</a></p>
<p>A couple of weeks ago, I started digging into the <a href="http://www.w3.org/TR/webaudio/">Web Audio API</a>. Initially, I was just looking to find out what it was and see if any ideas for toys presented themselves but, kinda predictably, I ended up getting elbow-deep in a bucketful of audio routing graphs, gain nodes and impulse responses.</p>

<p>I'll write up a more detailed post about the API shortly but <a href="http://blog.marcon.me/">Max</a> and I used it quite heavily in the <a href="http://hackathon.5apps.com/">5apps hackathon</a> we attended last week and I wanted to share the outcome of our hacking.</p>

<h2>SoundScape</h2>
<p><em>&ldquo;A Nokia Map mashed together with a bunch of APIs and positional audio to create an immersive map experience.&rdquo;</em></p>

<p>For a better explanation of how SoundScape works, check out Max's slides:</p>
<ul><li><a href="http://mmarcon.github.com/slides/soundscape/">http://mmarcon.github.com/slides/soundscape/</a></li></ul>
<p>In essence, we use a <a href="http://api.maps.nokia.com/">Nokia Map</a> as the base, add on a Flying Hamster, make a call to <a href="http://www.freesound.org/docs/api/">Freesound.org</a>  for geotagged audio samples, male a call to <a href="http://www.last.fm/api">LastFM</a> for upcoming concerts, make a call to <a href="http://developers.deezer.com/api">Deezer</a> for the most popular track by the artist playing the event reported by LastFM and put them all together in the browser using <a href="https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html">3D positional audio</a>. Basically.</p>

<p>The source is <a href="https://github.com/mmarcon/htm5Hackathon
">available on GitHub</a></p>

<h2>The Actual Demo</h2>
<p><a href="http://soundscape.nodester.com">SoundScape (Web Audio API-capable browser required)</a></p>      </div>
]]></description>
<pubDate>Sat, 12 May 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Web Audio</title>
<link>http://thingsinjars.com/post/458/web-audio/</link>
<guid>http://thingsinjars.com/post/458/web-audio/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-458">
        <p><a href="http://thingsinjars.com/post/458/web-audio/">Web Audio</a></p>
<p>I'm getting a bit obsessed with the <a href="http://en.wikipedia.org/wiki/HTML5_Audio#Web_Audio_API">Web Audio API</a> just now. That's not a bad thing, of course, I just wish the <a href="http://html5test.com/compare/feature/webaudio-webaudio.html">browsers would all catch up</a>.</p>

<p><a href="http://thingsinjars.com/post/459/sounds-like-a-hackathon/">Ages ago</a>, I mentioned the <a href="http://soundscape.nodester.com/">SoundScape</a> maps mashup <a href="http://marcon.me/">Max</a> and I made at the 5apps hackathon. Finally, here's the video of the two of us presenting it at a Nokia Berlin Tech Talk.</p>

<ul>
<li><a href="https://vimeo.com/46217788">Web Audio intro and SoundScape</a></li>
</ul>

<h2>Creative tutorials</h2>
<p>This goes along with the series of <a href="http://creativejs.com/resources/">Web Audio API introductory tutorials</a> I'm writing over at <a href="http://creativejs.com">CreativeJS</a>.</p>      </div>
]]></description>
<pubDate>Mon, 23 Jul 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Superhero Libraries</title>
<link>http://thingsinjars.com/post/455/superhero-libraries/</link>
<guid>http://thingsinjars.com/post/455/superhero-libraries/</guid>
<description><![CDATA[
        <div class="teaser " id="teaser-455">
        <p><a href="http://thingsinjars.com/post/455/superhero-libraries/">Superhero Libraries</a></p>
I'm currently writing an introduction course to JS libraries and have decided jQuery is like Batman – Objects are wrapped in a utility belt that does everything but are essentially unchanged underneath – while Prototype is more like Wolverine – Objects are injected with stuff to make them better, stronger, more deadly.

Anyone got any ideas about MooTools?      </div>
]]></description>
<pubDate>Mon, 05 Mar 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>JS Minification is seriously addictive.</title>
<link>http://thingsinjars.com/post/452/js-minification-is-seriously-addictive/</link>
<guid>http://thingsinjars.com/post/452/js-minification-is-seriously-addictive/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-452">
        <p><a href="http://thingsinjars.com/post/452/js-minification-is-seriously-addictive/">JS Minification is seriously addictive.</a></p>
<p>Having gotten hooked on it during the first <a href="http://js1k.com/">js1k</a>, written about <a href="http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/">extreme JS minification</a> and submitted a bunch of stuff to <a href="http://140byt.es/users/thingsinjars">140bytes</a>, I think it's fairly safe to say I'm an addict. Because of that, there was really no chance that I could let this year's js1k go by without entering.</p>

<p>The theme this year is &lsquo;<a href="http://js1k.com/2012-love/">Love</a>&rsquo;. Seeing as I never actually submitted my <a href="http://thingsinjars.com/post/296/maze-1k/">maze1k</a> demo, I decided I'd spruce it up, restyle a bit and submit it covered top to bottom in hearts. </p>

<p>There's not a lot I can say about minification techniques that hasn't already been covered either on <a href="http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/">this</a> <a href="http://thingsinjars.com/post/296/maze-1k/">site</a>, on <a href="http://marijnhaverbeke.nl/js1k/">Marijn Haverbeke's site</a>, on <a href="http://benalman.com/news/2010/08/organ1k-js1k-contest-entry/">Ben Alman's</a> or on the <a href="https://github.com/jed/140bytes/wiki/Byte-saving-techniques">140bytes wiki page on byte-saving techniques</a>. The only things I will add are a couple of techniques which are new to me. I have thoroughly commented the code below, however. If you want to play along, have a look.</p> 

<h2>Left-first Evaluation</h2>
<p>It's a feature of most programming languages that when you have a logical operator such as <code>&amp;&amp;</code> or <code>||</code>, the value of the left side of the operator determines whether the right side will be evaluated at all. If the left side of an AND is false, we're going to get a false for the whole thing. It doesn't matter what the right side is so we don't even need to look at it. Similarly, if the left side of an OR is true, the eventual return value will be true so we don't need to look at the right. For example, here are two statements:</p>

<pre><code>coffee&amp;&amp;morning
wine||work
</code></pre>

<p>In the first example (<code>&amp;&amp; &ndash; AND</code>), we will <em>only</em> check <code>morning</code> if <code>coffee</code> is true. We first have a look at <code>coffee</code> and if it is false, we don't care whether morning is true or not, we just skip it (and, presumably, go back to bed). If <code>coffee</code> is <code>true</code>, we'll then have a look to see if morning is true. It doesn't matter if morning is a function or a variable assignment or whatever, it will only happen if <code>coffee</code> is true.</p>
<p>In the second example (<code>|| &ndash; OR</code>), we will only evaluate <code>work</code> if <code>wine</code> is false. We start by looking at and evaluating <code>wine</code>. If that is true, the JS interpreter saves us from even considering <code>work</code> and skips it. The right-side of the operator, <code>work</code>, is only considered if wine is false.</p>
<p>You can probably see how, in a few simple situations, this can help avoid an <code>if()</code>, thereby saving at least one byte. Usually.</p>

<h2>&lsquo;A&rsquo; font</h2>
<p>If you want to set the font-size on a canvas 2D context, you have to use the font property. Makes sense, right? Unfortunately for obsessive minifiers, you can't <em>just</em> set the fontSize, you also have to set the fontFamily at the same time:</p>
<pre><code>canvas.getContext('2d').font="20px Arial"</code></pre>
<p>Failure to set the font family means that the whole value is invalid and the font size isn't applied.</p>

<p>My thought process: &ldquo;But 'Arial'? The word's so&hellip; big (5 bytes). There must be some way to make this smaller. If only there were a font called &lsquo;A&rsquo; (1 byte)&hellip;&rdquo;</p>

<p>Well, it turns out, if you set a font that doesn't exist on the user's system, the canvas will fall back on the system sans-serif by default. On windows that is... Arial. On OS X, it's Helvetica. I'm glad about that because otherwise, Helvetica wouldn't get a look-in, being 9 whole bytes.</p>
<p>There is always the chance that someone will have a font called &lsquo;A&rsquo; but I'm willing to take that risk. This possibility could be avoided by using an unlikely character like &#9829; for the font name.</p>

<h2>The code</h2>
<p>These are hosted on <a href="https://gist.github.com/1740736">GitHub</a> rather than in my usual code blocks to make it easier for you to fork them, pull them apart and get elbow-deep in them.</p>
<h3>The almost-impossible-to-read minified submission:</h3>

<h3>The full, unminified code with thorough commenting:</h3>



<h2>The submission</h2>
<p>My entry is up on the <a href="http://js1k.com/2012-love/demo/1028">js1k site now</a>. It's already getting quite busy up there after only a few days and I have to say I'm impressed by the fantastic job <a href="https://twitter.com/#!/kuvos">@kuvos</a> has done in building it up over the last couple of years and providing me with fuel for my addiction.</p>      </div>
]]></description>
<pubDate>Tue, 07 Feb 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>ImpressJS Tools</title>
<link>http://thingsinjars.com/post/448/impressjs-tools/</link>
<guid>http://thingsinjars.com/post/448/impressjs-tools/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-448">
        <p><a href="http://thingsinjars.com/post/448/impressjs-tools/">ImpressJS Tools</a></p>
<p>While putting together last week's <a href="http://thingsinjars.com/post/446/museum140-shorty/">promo video for Museum140</a> (a vote'd be awsm, btw), I knocked up a few tools to make my life easier. As I always say, if you find something you like, make a plugin for it. Seriously, I <strong>always</strong> say that. That might even be how I proposed to my wife, I'll have to check.</p>

<p>Anyway.</p>

<h2>Play</h2>
<p>This is a simple timing helper. It just provides a little array you can push slide durations into and at the end, you call 'play'. I can't see many uses for this other than in creating videos.</p>
<pre><code>ImpressJS.play(3000);  //Set the first slide duration for 3 seconds
ImpressJS.play(1000);  //Set the second slide duration for 1 second
ImpressJS.play(); //Play from the start
</code></pre>

<h2>Edit</h2>
<p>This is much more useful.</p>

<p>If this script is included in the page (after the impress.js script), you can drag your slides around, rotate and scale them into exactly the position you want. Once you're happy, you can get the current HTML output onto the console for pasting back into your original slideshow file. I could have snuck in a <a href="http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/">drag-n-drop file handler</a> but that would make it Chrome only.</p>


<h2>Disclaimer</h2>
<p>These tools rely on ImpressJS having a public API which it currently doesn't have. It's obviously high on the author's priority list (given the <a href="https://github.com/bartaz/impress.js/issues/39">amount of discussion</a> it's raised) but, as too many pull requests spoil the broth, I've made a <a href="https://github.com/thingsinjars/impress.js">little fork of my own</a>, added the public functions the tools require and I'll update them once the main repository's settled down a bit.</p>

<h2>Download</h2>
<p>These are available in the tools folder of this <a href="https://github.com/thingsinjars/impress.js">fork of impress.js</a>. Each one contains an example. Hopefully, these will be updated to use the public API as soon as it's available.</p>
      </div>
]]></description>
<pubDate>Mon, 16 Jan 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Umpteen ways to test for a function</title>
<link>http://thingsinjars.com/post/445/umpteen-ways-to-test-for-a-function/</link>
<guid>http://thingsinjars.com/post/445/umpteen-ways-to-test-for-a-function/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-445">
        <p><a href="http://thingsinjars.com/post/445/umpteen-ways-to-test-for-a-function/">Umpteen ways to test for a function</a></p>
<p>After wrestling with another <a href="http://140byt.es/" title="140byt.es">140bytes</a> challenge, I found myself wondering how many different ways you can test an object in JS to see if it&rsquo;s a function. I wrote out a few of them then threw it out to my colleagues who came up with a few more. I&rsquo;d love to hear from anyone who can suggest more to add to the list. Ideally, you want to find a test that will return true for all functions and only for functions. It&rsquo;d be great if it&rsquo;s a universal test that can be slightly modified to test for other types but that&rsquo;s not essential.</p>

<p><strong>Bear in mind, most of these shouldn&rsquo;t be used in the real world, this is just for fun.</strong></p> 

<p>There are a couple of main categories and several variations within.</p>

<h2>Duck Typing</h2>
<p>When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.</p><a href="http://en.wikipedia.org/wiki/Duck_test">The Duck Test</a>
<p>In other words, if an object has the methods of a function and the properties of a function, it&rsquo;s probably a duck. No, that doesn&rsquo;t sound right.</p>
<p>This simply detects whether the object we&rsquo;re testing contains the methods or properties we&rsquo;d normally associate with a function. The most common test is checking whether <code>a.call</code> exists. In most cases, this will only be defined on a function and it will be defined on all functions. It is, therefore, a good test to use.</p>

<p>The downside is that it can be fooled by setting a property of call on the object to be truthy. This will pass the test but still not be a function. Also, if the object is null or undefined, this will throw a TypeError (as pointed out by <a href="https://gist.github.com/1466219#gistcomment-71121">subzey on git</a>).</p>

<pre><code>a.call                   // Hey, this has a call property. Quack?
a.call &amp;&amp; a.call.call    // The call also has a call so is probably also a function. Quack.
a.apply                  // As before but with apply this time
a.apply &amp;&amp; a.apply.apply // ditto and ditto
</code></pre>

<h2>String comparisons on typeof</h2>
<p>This area of inspection is probably the richest for coming up with silly ideas to test. The <code>typeof</code> operator simply returns a string containing the type of the object. That&rsquo;s it. Anything you can think of to compare a string against another string, be it RegEx, charAt, equals or threequals (===) can be manipulated to become a check for type.</p>
<pre><code>typeof a>'f'&amp;&amp;typeof a&lt;'g'   // Long-winded and quite silly. Performs a numerical comparison on the strings
(typeof a).charAt(0)=='f'    // Sturdy but not very useful.
typeof a==typeof eval        // May as well use eval for something, it&rsquo;s a global function
typeof a==typeof dir         // Shorter but might not exist everywhere
typeof a=='function'         // The usual way to test. Everything above here is purely academic
/^f/.test(typeof a)          // Matching the string against a unique RegEx. See the table below
typeof a==typeof b           // Requires access to another variable which is a known function
(typeof a)[0]=='f'           // Small and robust but doesn&rsquo;t work in IE6 or 7
</code></pre>

<h3>Table of RegEx Patterns to match object types:</h3>
<p>As little aside here, we&rsquo;ve got a table of simple RegEx tests that do the same as the one mentioned above. They return true if the type is what you expect, false for all other types. They work by assuming things like &lsquo;object&rsquo; being the only type to contain a &lsquo;j&rsquo; or &lsquo;boolean&rsquo; being the only one with an &lsquo;a&rsquo;.</p>
<pre><code>Type         RegEx                 Note
boolean      /a/.test(typeof a)    // Shorter than typeof a==&lsquo;boolean&rsquo;
function     /^f/.test(typeof a)   // Shorter than typeof a==&lsquo;function&rsquo;
undefined    /d/.test(typeof a)    // Shorter than typeof a==&lsquo;undefined&rsquo;
number       /m/.test(typeof a)    // Same length as typeof a==&lsquo;number&rsquo;
object       /j/.test(typeof a)    // Same length as typeof a==&lsquo;object&rsquo;
string       /s/.test(typeof a)    // Same length as typeof a==&lsquo;string&rsquo;
null         /ll/.test(typeof a)   // Longer than typeof a==&lsquo;null&rsquo;
</code></pre>

<h2>Pick &amp; Mix</h2>
<p>This not only makes the assumption that an object is probably a function if it contains a &lsquo;call&rsquo; but also that if that call has the same type as the object, they&rsquo;re both probably functions.</p>
<pre><code>typeof a==typeof a.call      // A mixture of typeof string comparison and duck typing</code></pre>

<h2>instanceof</h2>
<p>In some circumstances, <code>instanceof</code> is going to be better than typeof as it compares types rather than strings.</p>
<pre><code>a instanceof Function      // This will throw a ReferenceError if a is undefined.</code></pre>

<h2>The [[Class]] of the object</h2>
<p>This comes from the <a href="http://bonsaiden.github.com/JavaScript-Garden/#types.typeof" title="typeof at JavaScript Garden">JavaScript Garden</a> where you&rsquo;ll find they have a strong opinion on <code>typeof</code> and <code>instanceof</code>. This uses <code>call</code> to execute the <code>toString</code> method on the <code>prototype</code> of the basic <code>Object</code> constructor. Phew. At that point, you'd have a string &lsquo;<code>[Object Function]</code>&rsquo;. You can then chop off the beginning and the end using slice (treating the string as if it were an array) to get just the type. All together, it looks like this:</p>
<pre><code>Object.prototype.toString.call(a).slice(8, -1);</code></pre>

<h2>Testing the string representation of the object</h2>
<p>This is fairly nasty but still quite effective. Convert the object itself to a string (not its type but the actual object) and see if that begins with &lsquo;function&rsquo;. This is nowhere nearly as robust as some of the other tests as this will also pass true for any strings that begin "function..." but it&rsquo;s quite cunning. Credit goes to <a href="http://twitter.com/mmarcon">Max</a> for this one.</p>
<pre><code>/^function/.test(a.toString())   //Test if the output of .toString() begins with &lsquo;function&rsquo;
/^function/.test(a+"")           //As above but using a shortcut to coerce the function to a string.
</code></pre>

<h2>Running it</h2>
<p>This isn&rsquo;t so much checking whether it looks and sounds like a duck, this is more like serving it <em>&agrave; l&rsquo;orange</em> and seeing if it tastes like a duck. The idea here is to actually try and execute it. If it throws an error, it&rsquo;s not executable, if it doesn&rsquo;t, it is. Or something like that. Here, we&rsquo;re testing that the error is an <code>instanceof</code> TypeError as an undefined object would also end up in the catch.</p>
<p>The obvious downfall to this technique is that you don&rsquo;t necessarily want the function executed when you&rsquo;re testing it. In fact, you almost never want to do that. I might go as far as to say you <strong>never</strong> want that.</p>
<pre><code>try {
  a();
  true;
} catch (e) {
  !(e instanceof TypeError);
}
</code></pre>
<p>The other big weakness in the above technique is that, even if the object is a function, the call itself might throw a TypeError. In Chrome, there's a bit more transparency as the error thrown has a type property. In that case you want to check that the type is <code>'called_non_callable'</code> but that might still be a consequence of the function. In Safari, there's a similar property on the error (<code>e.message</code>) but the error object itself is no longer a TypeError, it is just an Error.</p>

<h2>More&hellip;</h2>
<p>I&rsquo;m certain there are more. Many, many more. There are also several dozen that are trivial variations on those mentioned above &ndash; you could do the same string comparison tests on the <code>[[Class]]</code> property, for instance &ndash; but I missed these out. There&rsquo;s probably a huge section missed out here (I'd forgotten <code>instanceof</code> existed until after the first draft of this post, for instance). If you can think of any more, let me know here or on <a href="https://twitter.com/intent/tweet?text=@thingsinjars%20Yo,">The Twitter</a>.</p>
<p>I'll also reiterate my point from earlier: most of these are deliberately useless or inefficient. The point here isn't to find better ways to do things, it's to practice doing what you do every day. The more you <em>play</em> while being a web developer, the less you need to <em>work</em>.</p>      </div>
]]></description>
<pubDate>Mon, 09 Jan 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Latest 140byt.es offerings</title>
<link>http://thingsinjars.com/post/442/latest-140bytes-offerings/</link>
<guid>http://thingsinjars.com/post/442/latest-140bytes-offerings/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-442">
        <p><a href="http://thingsinjars.com/post/442/latest-140bytes-offerings/">Latest 140byt.es offerings</a></p>
<p>Long-term readers (a.k.a. my Mum) might remember my <a href="http://js1k.com/">JS1K</a> <a href="http://thingsinjars.com/post/296/maze-1k/">efforts</a> <a href="http://thingsinjars.com/post/292/elementally-my-dear-javascript/">last</a> <a href="http://thingsinjars.com/post/294/art-maker-1k/">year</a> and the subsequent discussion of <a href="http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/">Extreme JS Minification</a>. The same kind of mindset that inspired <a href="https://twitter.com/#!/kuvos">qfox</a> to create that competition also inspired <a href="https://twitter.com/#!/jedschmidt">Jed</a> to create <a href="http://140byt.es/">140 Bytes</a>. As with JS1K, the clue is in the name, you have the length of a tweet &ndash; 140 characters &ndash; to create something cool or clever in JS.</p>

<p>I won't go into any more detail here, if you're interested, you've either already heard about it or would do better clicking around the <a href="http://140byt.es/">140bytes site</a> or reading the comments on the <a href="https://gist.github.com/962807">master gist</a>.</p>

<h2>My entries</h2>
<p>Following last week's draggable file script, I started messing about with making it small enough to qualify and, predictably, got hooked. Here are four I made last weekend.</p>

<p>The scripts below are directly embedded from <a href="https://github.com/">GitHub</a> and are the minified, highly compressed versions. I recommend clicking through to the original gist for each of them where you'l find a file called <code>annotated.js</code> which talks through the code.</p>

<h3><a href="http://gist.github.com/1466219">Create a draggable file on-the-fly</a></h3>
<p>The code from <a href="http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/">last week</a> shrunk down. </p>


<h3><a href="http://gist.github.com/1460798">Detect Doctype</a></h3>
<p>There's no simple way to access the current document's doctype as a string. There is already a <code>document.doctype</code> object so you might expect (or, at least I'd expect) you could do a <code>.toString()</code> or <code>.asDoctypeString</code> or something like that. Nope. Nothing. You have to manually recreate it as a concatenation of properties. A quick discussion with <a href="http://twitter.com/kirbysayshi">kirbysayshi</a> and <a href="http://twitter.com/mmarcon">mmarcon</a> came up with a few alternative methods (Max's is quite devious, actually) before eventually culminating in this.</p>


<h3>Chainify and Propertize</h3>
<p>This began as a very minimal implementation of <a href="https://twitter.com/#!/leaverou">Lea Verou's</a> <a href="http://lea.verou.me/chainvas/">Chainvas</a>. The idea is to enhance various constructors (Element, Node, etc.) so that each method returns the original object. This means that you can then chain (jQuery-style) any built-in function. Each constructor is also enhanced with a .prop function which allows property setting in a similarly chainable manner. For a better description, read through <a href="http://lea.verou.me/chainvas/">the Chainvas site</a>. </p>


      </div>
]]></description>
<pubDate>Sat, 17 Dec 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Create a draggable file on-the-fly with JS</title>
<link>http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/</link>
<guid>http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-440">
        <p><a href="http://thingsinjars.com/post/440/create-a-draggable-file-on-the-fly-with-js/">Create a draggable file on-the-fly with JS</a></p>
<p>Here's a useful little code snippet if you're building a web application. It's a simple way of making the boundary between web-browser and platform a bit smaller. It allows you to create a file (text, html, whatever) in in your page which the user can drag onto their desktop (if their browser supports the dragstart event and dataTransfer methods).</p>

<pre><code>document.getElementById('downloadElement').addEventListener("dragstart", function (e) {
  e.dataTransfer.setData("DownloadURL", "text/html:filename.html:data:image/png;base64," + btoa(fileContent));
});
</code></pre>

<p>A description of the code:</p>
<ul>
 <li>attach an event listener to the draggable element you specify (<code>downloadElement</code>)</li>
<li>when you start to drag it (<code>dragstart</code>),</li>
<li>it creates a dataTransfer object (with the type <code>DownloadURL</code>)</li>
<li>and sets the content of that to be whatever you pass it (<code>fileContent</code>)</li>
<li>It uses <code><a href="https://developer.mozilla.org/en/DOM/window.btoa">btoa()</a></code> to encode the string data as a base64-encoded string.</li>
<li>When you combine this with the MIME-type (<code>text/html</code>),</li>
<li>you can create a file with the specified name (<code>filename.html</code>) when the user releases the drag in their local file system.</li>
<li>The fake MIME-type (<code>image/png</code>) is there as part of the object data to convince the browser this is a binary file (which it is, even though it's not an image).</li>
</ul>

<p>Note: The element this is attached to (<code>downloadElement</code> above) should either be draggable by default (image, link or text selection) or have the draggable attribute set otherwise this'll do nothing.</p>

<p>Credit goes to <a href="http://paul.kinlan.me/">Paul Kinlan</a> for using this in <a href="http://appmator.appspot.com/">Appmator</a> which is where I first saw this done this way. He actually uses it alongside some extremely clever JS zip-file creation stuff, too, it's definitely worth digging through the source there.</p>

<p>You can find out more about the drag events on the <a href="https://developer.mozilla.org/En/DragDrop/Drag_Operations">MDN</a>.</p>      </div>
]]></description>
<pubDate>Thu, 08 Dec 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Simple and clever beats clever</title>
<link>http://thingsinjars.com/post/439/simple-and-clever-beats-clever/</link>
<guid>http://thingsinjars.com/post/439/simple-and-clever-beats-clever/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-439">
        <p><a href="http://thingsinjars.com/post/439/simple-and-clever-beats-clever/">Simple and clever beats clever</a></p>
<p>When messing about with another little game idea, I found myself retyping (for the umpteenth time) the same little bit of value bounding code I use a lot:</p>

<pre><code>var x = Math.max(0, Math.min(y, 1))</code></pre>

Which basically translates to:

<pre><code>"Set x to be the value of y as long as it's between 0 and 1. 
If not, set it to 
  0 if it's smaller or 
  1 if it's larger."</code></pre>

<p>Of course, 0 and 1 don't need to be the boundaries, I'm just using them for convenience.</p>

<p>Instead of continuing with the game, I decided to take a little tangent and see if there was any way I could rewrite this so that the syntax was a bit more obvious. I'd like to be able to use syntax like:</p>

<pre><code>x = [0 &lt; y &lt; 1]</code></pre>

<p>to mean the same. Written exactly as above, JS will try and evaluate left-to-right, changing the comparisons to booleans. The statement would become</p>

<pre><code>y = 0.5

x = [0 &lt; y &lt; 1]
x = [0 &lt; 0.5 &lt; 1]
x = [true &lt; 1]
x = [false]</code></pre>

<p>Similarly:</p>

<pre><code>y = -0.5

x = [0 &lt; y &lt; 1]
x = [0 &lt; -0.5 &lt; 1]
x = [false &lt; 1]
x = [true]</code></pre>

<p>My first thought was to be clever about it, I wanted to try and figure out how to partially evaluate the expression and take the different outcomes to figure out the logic required. If '0 < y' was false, then y is less than zero therefore outside our bounds, the return value should then be 0. If the first part is true and the second is false then we know the value is higher than our bounds....etc and so on.</p>

<p>This proved to be a logical dead-end as there was no good way to partially evaluate the statements. Not without preparsing the JS, anyway. Which leads me onto the second attempt...</p>

<h2>Preparsing the JS</h2>

<p>The next attack on the problem was the idea of reading the JS as a string, shuffling it around quickly and silently (not like a ninja, more like a speedy librarian in slippers) and put it back where it was.</p>

<p>So I began to look at ways to recreate that. I remembered from many, many years ago (two, actually) <a href="http://alexsexton.com/" title="AlexSexton.com">Alex Sexton</a> creating the genius abomination that is <a href="http://summerofgoto.com/" title="The Summer of Goto | Official Home of Goto.js">goto.js</a> and how that used some kind of preparsing. A quick skim through the code later and I ended up on <a href="http://james.padolsey.com/" title="Home &ndash; James Padolsey">James Padolsey's site</a> looking at <a href="https://github.com/padolsey/parseScripts">parseScripts.js</a>.</p>

<p>In the end, all I needed to do was include parseScripts (which is a generalised form of the code I ended up using for the <a href="http://thingsinjars.com/post/424/whitehat-syndication/" title="">whitehat SEO question</a> from last month) and provide a new parser function and script type.</p>

<pre><code>parseScripts(/:bound/, function(unparsed) {
 return unparsed.replace(/\[(\d)\s*&lt;\s*(\w)\s*&lt;\s*(\d)\]/g, "Math.max($1, Math.min($2, $3))");
})</code></pre>

<p>I'm not saying parseScript isn't clever because it most definitely is but I am saying it's simple. There's not always a need to branch off into deep technical investigations of partial evaluation when a simple search-and-replace does the job better and faster.</p>

<p>For someone always going on about bringing simplicity and pragmatism into development, you'd think I'd have gotten there faster...</p>

<h2>Bounded Range</h2>
<p>The final <a href="http://thelab.thingsinjars.com/bounded/">bounded range syntax code is available here</a> (hint: view the console). It's silly but it was a fun half-hour.</p>

<h2>Improvements?</h2>
<p>Do you know of any better way to do this? Is there a clever parsing trick we can use instead? Is there, indeed, any language which has this syntax?</p>
      </div>
]]></description>
<pubDate>Sat, 03 Dec 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>cssert – Like ‘assert’ but with CSS at the front</title>
<link>http://thingsinjars.com/post/438/cssert--like-assert-but-with-css-at-the-front/</link>
<guid>http://thingsinjars.com/post/438/cssert--like-assert-but-with-css-at-the-front/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-438">
        <p><a href="http://thingsinjars.com/post/438/cssert--like-assert-but-with-css-at-the-front/">cssert – Like ‘assert’ but with CSS at the front</a></p>
<p>This continues on from my post about <a href="http://thingsinjars.com/post/437/cssert---css-verification-testing/">CSS verification testing</a></p>

<p>cssert – pronounced however you feel like it – is my attempt at bringing some kind of style verification into an automated build process. If you've read <a href="http://thingsinjars.com/post/437/cssert---css-verification-testing/">the previous article</a>, you'll know that this falls into the second group of CSS test frameworks, style measurement and comparison. The system works exactly as I described above – your test files have a basic HTML structure created by traversing the DOM from the element being tested upwards. You could also include your entire HTML in the test file if you liked, it would just be unnecessary in most cases.</p>

<p>I've created a couple of (for me, at least) helpful utilities which allow these test cases to be generated from a page via a bookmarklet and then run in the browser or on the command-line. Running the tests in the browser is useful for quick human verification while the command-line interface can be integrated into an automated build system if you like that kind of thing. The test file structure is quite simple (all samples here taken from the <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap project</a>:</p>
<p>First, we have the test file opening structure:</p>
<pre><code>&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;cssert test page&lt;/title&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;../lib/cssert.css&quot;&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;cssert Test cases&lt;/h1&gt;&lt;p&gt;click to expand test&lt;/p&gt;&lt;script type=&quot;text/html&quot;&gt;/*==</code></pre>
<p>Then we have the name of the test:</p>
<pre><code>Intro Paragraph</code></pre>
<p>Then we have the skeleton DOM:</p>
<pre><code>&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;base href=&quot;http://twitter.github.com/bootstrap/examples/hero.html&quot;&gt;&lt;link href=&quot;../1.3.0/bootstrap.css&quot; rel=&quot;stylesheet&quot;&gt;&lt;style type=&quot;text/css&quot;&gt;
      body {
        padding-top: 60px;
      }
    &lt;/style&gt;&lt;style&gt;#cssert-style-modal {display:none;position: fixed;top: 10%;left: 50%;margin-left: -350px;width: 700px;background: #39c;color: white;padding: 10px;color: #fff;text-shadow: 0 1px 0 rgba(0,0,0,.3);background-image: -webkit-linear-gradient(-45deg, rgba(255,255,255,0), rgba(255,255,255,.1) 60%, rgba(255,255,255,0) 60%);border-radius: 5px;border: 1px solid #17a;box-shadow: inset 0 0 0 1px rgba(255,255,255,.3);}#cssert-style-modal ul,#cssert-style-modal li {margin:0;padding:0;font-size:11px;list-style:none;}#cssert-style-modal&gt;ul&gt;li {float:left;width:140px;font-size:13px;}#cssert-style-modal ul {margin-bottom:10px;}#cssert-pre {position:fixed;top:10px;right:10px;background:white;border:1px solid gray;width:200px;height:200px;overflow:auto;}#cssert-drag {position:fixed;top:210px;right:10px;background:white;border:1px solid gray;width:200px;height:20px;overflow:auto;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class=&quot;container&quot;&gt;&lt;div class=&quot;hero-unit&quot;&gt;&lt;p&gt;Vestibulum id ligula porta felis euismod semper. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>
<p>The CSS selector identifying the element to verify:</p>
<pre><code>html body div div p</code></pre>
<p>And the styles we wish to verify:</p>
<pre><code>{"font-family":"'Helvetica Neue', Helvetica, Arial, sans-serif","font-weight":"200","font-style":"normal","color":"rgb(64, 64, 64)","text-transform":"none","text-decoration":"none","letter-spacing":"normal","word-spacing":"0px","line-height":"27px","text-align":"-webkit-auto","vertical-align":"baseline","direction":"ltr"}</code></pre>
<p>A test file can contain as many test units as you like. At the very end is the close of the test file structure</p>
<pre><code>*/&lt;/script&gt;&lt;script src=&quot;../lib/cssert.js&quot;&gt;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>
<p>You'll probably notice the crucial bit in the test structure is the <code>base</code> element. The CSS available from the location specified here is the thing we are actually testing. In typical test lingo, the structure we have in our test file is the mock and our tests work by asserting the values &lsquo;output&rsquo; from applying the CSS to this structure are as expected.</p>

<h2>Running the tests</h2>
<h3>Running the tests in-browser</h3>
<p>Open the test page in a browser. That's it. If it's green and says 'passed', the test passed. If it's red and says 'failed', the test failed. You can see the output by clicking on the title of the test.</p>
<p>This works by loading the test file, creating an iframe and injecting the test case into the iframe as source. It then looks into the iframe and measures the styles. If they match those specified in the test file, it passes, otherwise, it fails. Clicking on the test title simply removes the <code>position:absolute</code> which is hiding the iframe.</p>
<h3>Running the tests on command-line</h3>
<p>The exact same test page can also be used with the command-line interface. cssert uses <a href="http://phantomjs.org">PhantomJS</a> to run the tests in a headless webkit instance. You'll need to install PhantomJS into your path after downloading it. Place your test case in the tests folder and run:</p>
<pre><code>$ ./cssert testcase.html</code></pre>
<p>To run all tests in the tests folder at once, simply run with no arguments:</p>
<pre><code>$ ./cssert</code></pre>
<p>This works by, again, loading the HTML from the test files. In this case, the structure is injected into a new headless browser window. The styles are measured and the output is redirected to stdout. Each browser window test is also rendered as a PNG so you can see what failed if any did.</p>

<h2>Limitations</h2>
<p>I'm not saying this is the ultimate solution to CSS testing. Declarative languages don't sit well with testing. This is as close as I can get for the moment. I'm also not going to be able to head off or counter all possible complaints or criticisms but I will cover a couple.</p>
<p>Firstly, most of the limitations you'll run into are caused by using the automatically generated tests. They're good for creating a starting point but at the moment, they need to be tweaked for many cases.</p>
<h3>Sibling selectors</h3>
<p>Because the test generates the DOM via following parents up the structure, sibling elements are ignored. These styles are still testable, though. Simply add the sibling element into your HTML test block.</p>
<h3>Styles modified by JS</h3>
<p>The styles are measured on the element as it is when the case is generated. The test compares this against the styles provided by the CSS. If the element contains JS-only styles not added by CSS, they will not be correctly matched. Modify your test case to allow for this.</p>
<h3>Why not use Selenium?</h3>
<p>This, essentially does the same as Selenium would do if you took the time to set up your test cases. This makes it much easier to set up test cases, though.</p>
<h3>@font-face!</h3>
<p>If your @font-face declaration contains a suggested 'local' source (as recommended in Paul Irish's <a href="http://paulirish.com/2009/bulletproof-font-face-implementation-syntax/">bulletproof syntax</a>), a <a href="https://bugs.webkit.org/show_bug.cgi?id=36351">bug in QTWebkit</a> will prevent the test case from running correctly.</p>

<h2>Installation</h2>
<p>Just clone the git project from <code>git@github.com:thingsinjars/cssert.git</code> and you're good to go.</p>
<p>The tests directory comes with some sample tests generated using Twitter's Bootstrap project. Put your tests in that same place.</p>      </div>
]]></description>
<pubDate>Mon, 28 Nov 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>CSS Verification Testing</title>
<link>http://thingsinjars.com/post/437/css-verification-testing/</link>
<guid>http://thingsinjars.com/post/437/css-verification-testing/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-437">
        <p><a href="http://thingsinjars.com/post/437/css-verification-testing/">CSS Verification Testing</a></p>
<p>It&#x27;s difficult to test CSS. In <a href="http://maps.nokia.com/">Nokia Maps</a>, we use lots of different kinds of automated tests to ensure the build is doing what it&#x27;s supposed to do &ndash; <a href="http://pivotal.github.com/jasmine/">Jasmine</a> for JS unit tests, <a href="http://jbehave.org/">jBehave</a> for Java acceptance tests, a whole load of integration tests and systems to make sure all along the process that we know as soon a something goes wrong.</p>

<p>CSS has typically been left out of this process &ndash; not just in our team but generally throughout the industry &ndash; because it&#x27;s a difficult thing to test. CSS is a declarative language meaning that the CSS of a page doesn&#x27;t describe how the page is to accomplish the task of turning text red, for example, it simply says &#x27;the text should be red&#x27; and the implementation details are left up to the browser. This doesn&#x27;t fit well into typical testing strategies as there is no sensible way to pass information in to check the outputs are as expected. With a declarative language, there is very little logic around which you can wrap a test. In essence, the bit you would normally test is the bit handled by the browser. About the closest CSS gets to having continuous-deployment style tests is to run your files against the in-house style guide using <a href="http://csslint.net/">CSSLint</a>.</p>

<p>That&#x27;s not to say people haven&#x27;t tried testing CSS. There are lots of opinions on how or why it should be done but with no concrete answers. There has also been a lot of thinking and quite a lot of work done in the past to try and solve this requirement. <a href="http://morethanseven.net/2008/10/13/unit-testing-css-looking-solution.html">This article from 2008</a> and <a href="http://blog.jonnay.net/archives/695-Unit-testing-CSS-and-HTML.html">this article from 2006</a> both propose a potential route to investigate for testing strategies.</p>

<p>In summary, the two main approaches used are:</p>
<ul>
<li>Generate images from the rendered HTML and compare differences (c.f. <a href="https://github.com/garethr/css-test">css-test by Gareth Rushgrove</a>)</li>
<li>Specify expected values and compare actual values (<a href="https://github.com/gagarine/CSSunit">cssUnit</a>, <a href="http://www.trisis.co.uk/blog/?p=356">CSSUnit</a>)</li>
</ul>

<p>There must be something about the desire to test CSS and the name Simon as both <a href="https://github.com/gagarine/CSSunit">Simon Perdrisat</a> and <a href="http://www.trisis.co.uk/blog/?p=356">Simon Kenyon Shepard</a> created (separate) unit-testing frameworks called &#x27;CSSUnit&#x27;. And there&#x27;s me, obviously.</p>

<p>As a related aside, there may also be something to do with working at Nokia and wanting to test CSS as Simon Shepard is the Tech Lead on Nokia Maps although I stumbled across his project completely randomly outside work. Weird.</p>


<p>Another important related note: there&#x27;s no point in developing a CSS testing framework for <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test-Driven Development</a>. Again, this is an aspect of being a declarative language but, by the time you&#x27;ve written your test, you&#x27;ve written your code. There&#x27;s no Red-Green pattern here. It either does what you intended it to or it doesn&#x27;t.</p>

<p>In essence, the only way to test CSS is by verification testing &ndash; the kind of thing you do before and after refactoring your styles. This, essentially, involves working within your normal process until the job is done then creating &#x27;snapshots&#x27; of the DOM and capturing the current cascaded styles. You can then refactor, rework and reorganise your CSS as much as you like and, as long as the combination of snapshot DOM plus CSS produces the same results as before, you can be confident that your entire system still appears the same way.</p>

<h2>Get to the point...</h2>
<p>Why the long ramble about CSS testing strategies? Well, unsurprisingly, I&#x27;ve had a go at it myself. My approach falls into the second category mentioned above &ndash; measure styles once finished and create secure test-beds of DOM structure which can have CSS applied to them. The test system is currently being run through its paces in <a href="http://maps.nokia.com/city/germany/berlin">Nokia Maps City Pages</a> (my bit of maps) and, if it passes muster, I&#x27;ll put it out into the big, wide world.</p>
      </div>
]]></description>
<pubDate>Wed, 28 Dec 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Super Mario Kart CSS</title>
<link>http://thingsinjars.com/post/434/super-mario-kart-css/</link>
<guid>http://thingsinjars.com/post/434/super-mario-kart-css/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-434">
        <p><a href="http://thingsinjars.com/post/434/super-mario-kart-css/">Super Mario Kart CSS</a></p>
<h2>Silly CSS Fun for a Sunday Afternoon</h2>
<p>Yesterday, I decided to mess around with 3D CSS transforms. I've used them here and there for various things (the flip animations in <a href="http://shelvi.st/thingsinjars">Shelvi.st</a>, for example) but nothing silly.</p>

<p>My mind wandered back to an early <a href="http://www.nihilogic.dk/labs/mariokart/">HTML5 canvas demo</a> I saw ages ago where Jacob Seidelin had written Super Mario Kart in JS and I wondered if it would be possible to do the pixel-pushing part of that demo in CSS.</p>

<p>An hour later and we have this:</p>
<p><a href="http://thelab.thingsinjars.com/CSSKart/">Super Mario Kart CSS</a></p>

<p>Yes, it's silly. Yes, it's nothing like playing Mario Kart and, no, there isn't any acceleration. That wasn't the point, however. View the source to see the description of the rotations and transforms.</p>      </div>
]]></description>
<pubDate>Mon, 14 Nov 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Poor man's touch interface</title>
<link>http://thingsinjars.com/post/433/poor-mans-touch-interface/</link>
<guid>http://thingsinjars.com/post/433/poor-mans-touch-interface/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-433">
        <p><a href="http://thingsinjars.com/post/433/poor-mans-touch-interface/">Poor man's touch interface</a></p>
<p>Here's a little code snippet for today.</p>

<p>While I was making the <a href="http://thingsinjars.com/post/434/super-mario-kart-css/">3D CSS Mario Kart</a>, I needed a simple, drop-in bit of code to handle touch interfaces. I looked through some old experiments and found a rough version of the code below. It was based on this <a href="http://stackoverflow.com/questions/3691461/remove-key-press-delay-in-javascript">KeyboardController</a> by Stack Overflow user <a href="http://stackoverflow.com/users/18936/bobince">Bob Ince</a>.</p>

<p>It doesn't do anything clever. All it does is provide a simple way to attach functionality to touch events in different areas of the screen &ndash; top-left, top-center, top-right, middle-left, middle-center, middle-right, bottom-left, bottom-center, bottom-right. My apologies to any Brits for the spelling of centre as 'center'. It's the Internet, we have to.</p>

<h2>How to use</h2>
<p>Include this code:</p>
<pre><code>
function TouchController(areas, repeat) {
  var touchtimer;
  document.onmousedown = document.ontouchstart = document.ontouchmove = function(e) {
    var position;
    e.preventDefault();
    e.touches = [{&#x27;clientX&#x27;:e.pageX,&#x27;clientY&#x27;:e.pageY}];
    switch(true) {
    case (e.touches[0].clientY&lt;window.innerHeight/3) : 
        position = &#x27;top&#x27;;
        break;
    case (e.touches[0].clientY&gt;(2*window.innerHeight)/3) : 
        position = &#x27;bottom&#x27;;
        break;
    default : 
        position = &#x27;middle&#x27;;
        break;
    }
    position+=&#x27;-&#x27;;
    switch(true) {
    case (e.touches[0].clientX&lt;window.innerWidth/3) : 
        position += &#x27;left&#x27;;
        break;
    case (e.touches[0].clientX&gt;(2*window.innerWidth)/3) : 
        position += &#x27;right&#x27;;
        break;
    default : 
        position += &#x27;center&#x27;;
        break;  
    }

    if (!(position in areas)) {
      return true;
    }

    areas[position]();
    if (repeat!==0) {
      clearInterval(touchtimer);
      touchtimer= setInterval(areas[position], repeat);
    }
    return false;
  };
  // Cancel timeout
  document.onmouseup = document.ontouchend= function(e) {
  clearInterval(touchtimer);
  };
};
</code></pre>

<p>Now, all you need to do to attach a function to a touch event in the top-left area of the screen is:</p>
<pre><code>TouchController({
  'top-left': function() { topLeftFunction();}
}, 20);
</code></pre>

<p>I use this for direction control in the Mario Kart experiment which maps exactly onto the cursor keys used for the normal control.</p>
<pre><code>TouchController({
  'top-left': function() {  // UP + LEFT
				drawMap.move({y: 2}); 
				drawMap.move({z: drawMap.z + 2}); 
				drawMap.sprite(-1) 
			  },
  'top-center': function() {  // UP
				drawMap.move({y: 2}); 
			  },
  'top-right': function() {  // UP + RIGHT
				drawMap.move({y: 2}); 
				drawMap.move({z: drawMap.z - 2}); 
				drawMap.sprite(1) 
			  },

  'middle-left': function() {  // LEFT
				drawMap.move({z: drawMap.z + 2}); 
				drawMap.sprite(-1) 
			  },
  'middle-right': function() {  // RIGHT
				drawMap.move({z: drawMap.z - 2});
				drawMap.sprite(1) 
			  },

  'bottom-left': function() {  // DOWN + LEFT
				drawMap.move({y:  - 2}); 
				drawMap.move({z: drawMap.z + 2}); 
				drawMap.sprite(-1)  
			  },
  'bottom-center': function() { 
				drawMap.move({y:  - 2}); 
			  },
  'bottom-right': function() {  // DOWN + RIGHT
				drawMap.move({y:  - 2}); 
				drawMap.move({z: drawMap.z - 2}); 
				drawMap.sprite(1)  
			  },
}, 20);
</code></pre>

<p>If you need anything clever or you need two or more touches, you should use something else. This is just a simple drop-in for when you're copy-paste coding and want to include touch-screen support.</p>
      </div>
]]></description>
<pubDate>Thu, 17 Nov 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Silly CSS Gradient</title>
<link>http://thingsinjars.com/post/432/silly-css-gradient/</link>
<guid>http://thingsinjars.com/post/432/silly-css-gradient/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-432">
        <p><a href="http://thingsinjars.com/post/432/silly-css-gradient/">Silly CSS Gradient</a></p>
<p>Okay, here's a bit of silliness. I did a little presentation yesterday with some slides which I built using <a href="http://hakim.se/">Hakim El Hattab's</a> 3D <a href="http://hakim.se/experiments/css/slideshow/#/">CSS Slideshow</a>. I decided to have some fun with the last slide. </p>

<p><a href="http://thelab.thingsinjars.com/thats-all.html">The Looney Tunes &ldquo;That's all Folks&rdquo;  end title using radial gradients</a>.</p>

<p>I was doing my presentation using Chrome so I'm allowing myself some leeway that it's not fully cross-browser.</p>      </div>
]]></description>
<pubDate>Tue, 08 Nov 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>jQuery Detach Scrollbars Plugin </title>
<link>http://thingsinjars.com/post/422/jquery-detach-scrollbars-plugin-/</link>
<guid>http://thingsinjars.com/post/422/jquery-detach-scrollbars-plugin-/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-422">
        <p><a href="http://thingsinjars.com/post/422/jquery-detach-scrollbars-plugin-/">jQuery Detach Scrollbars Plugin </a></p>
<p>tl;dr: I made a plugin: <a href="http://thelab.thingsinjars.com/detach-scrollbars/jquery.detach-scrollbar.min.js">jQueryDetach Scrollbars Plugin download [Zip &ndash; 1.4KB]</a></p>
<p>A design I recently worked on called for a scrollbar which only took up half the height of the area it was scrolling. Now, I'm not going to get into a discussion about scroll behaviour, accepted standards or user expectations - fascinating though that would be - instead, Here's a jquery plugin. </p> 

<p>The existing jQuery plugins I found that dealt with scrollbars created their own custom, themable bars. <a href="http://jscrollpane.kelvinluck.com/">jScrollpane</a>, for instance, gives you complete control over pretty much every aspect of the look and feel of the scrollbar. I figured this was too much for my needs, all I wanted was to be able to anchor the scrollbar to a given corner and change its height. <a href="http://thelab.thingsinjars.com/detach-scrollbar/">The resulting plugin</a> does just that. It even handles OS X Lion's disappearing scrollbars natively, too.</p> 

<h2>Usage</h2>
<p>Note: This currently only works on vertical scrolling and doesn't have a good jQuery setup and teardown. If I needed it more than once on a page, I'd have written it a bit more robustly so it could be used more than once. Maybe I'll leave that task as an exercise for the enthusiastic reader.</p>

<p>If you call the plugin on an element with a scrollbar (i.e. the element has height and contains content that overflows), it will duplicate the scrollbar using the standard browser scrollbar and get rid of the original one. In fact, in its default configuration, there's pretty much no difference between using the plugin and not using it.</p> 

<pre><code>$(element).detachScrollbar();</code></pre>

<p>It becomes more useful, however, when you pass in a couple of options. This example will move the scrollbar to the left of the content area:</p>
<pre><code>$(element).detachScrollbar({anchor : 'topleft'});</code></pre>

<p>You could leave the scrollbar on the right but shrink it downwards:</p>
<pre><code>$(element).detachScrollbar({anchor : 'bottomright', height : '50%'});</code></pre>

<p>The only behaviour of a standard scrollable area that isn't replicated by default is being able to use the mouse wheel to scroll while over the content area. If you want this behaviour (and you probably do), all you need to do is include the <a href="http://brandonaaron.net/code/mousewheel/docs">jQuery Mousewheel plugin</a> in your page. This script will recognise if it's available and enable the functionality.</p>

<h2>How it works</h2>
<p>The script creates a container div around the original scrollable content and sets that to <code>overflow:hidden</code> while setting the original area to <code>height:auto</code>. This means that the original scrollbar disappears. It then creates another invisible div the same height as the original content and wraps that in a div with <code>overflow-y:scroll</code>, this creates a scrollbar that looks exactly like the original one. Add in some clever event trickery to tie the scroll position of one to the scroll position of the other and we're done. We've replicated the original functionality but can now control the styles applied to the scrollbar completely separately from the original content. This means we can position it to the left or above, maybe add a 90&deg; CSS transform and have it look like a horizontal scrollbar, anything you like.</p>
<p>The plugin also incorporates &ldquo;Cowboy&rdquo; Ben Alman's <a href="http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth">scrollbar width plugin</a> to make sure we're matching dimensions on whatever platform this is used on.</p>

<p>The options that can be passed in are:</p>
<pre><code>internal: true / false (default: true)
autoposition: true / false (default: true)
anchor: 'topleft' / 'topright' / 'bottomleft' / 'bottomright' (default: 'topright')
height: Any CSS length (default '100%')</code></pre>

<h2>Advanced usage</h2>
<p>The <code>autoposition</code> option allows you to decide whether to let the plugin handle the layout (which you probably do for most cases) or whether you want to specify everything yourself using the provided classes as styling hooks.</p>

<p>The other option, <code>internal</code>, determines the DOM structure. Specifically, it says whether everything is contained within the one element or whether the scrollbar is separate. Specifying <code>internal: false</code> would allow you to put the scrollbar anywhere on your page. You could have all scrollbars set as <code>position: fixed</code> along the top of the page if you wanted. Not sure why you would but you could.</p>

<h2>Example and Download</h2>
<p><a href="http://thelab.thingsinjars.com/detach-scrollbar/">jQueryDetach Scrollbars Plugin</a></p>
<p><a href="http://thelab.thingsinjars.com/detach-scrollbar/jquery.detach-scrollbar.js">jquery.detach-scrollbars.js</a></p>      </div>
]]></description>
<pubDate>Fri, 09 Dec 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>You must be able to read before you get a library card</title>
<link>http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/</link>
<guid>http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-416">
        <p><a href="http://thingsinjars.com/post/416/you-must-be-able-to-read-before-you-get-a-library-card/">You must be able to read before you get a library card</a></p>
<p>I like JavaScript. JS. ECMAScript. Ol' Jay Scrizzle as nobody calls it.</p>

<p>I also like <a href="http://jquery.com/">jQuery</a>. jQ. jQuizzie. jamiroQuery. Whatever.</p>

<p>Ignoring the stoopid nicknames I just made up, did you notice how I referred to JavaScript and jQuery separately? I didn't say "I like JavaScript, there are some really great lightbox plugins for it" just the same as I didn't say "I wish there was a way to do indexOf in jQuery".</p>

<p>I'm regularly amazed at how many new (and some not-so-new) web developers either think they know JavaScript because they know jQuery or wish there was a way to do something in jQuery that they read about in an article about JavaScript. jQuery is a <em>library</em> written to make coding in JavaScript easier. It's made in JavaScript so you can say "jQuery is JavaScript" but only in the same way that "Simon is male". To confuse jQuery as all of JavaScript is the same as saying "Simon is all men" (don't worry, there's still only one of me).</p>

<p>For most web site or web app development, I do recommend using a library. Personally, I've used jQuery and <a href="http://www.prototypejs.org/">Prototype</a> extensively and decided I prefer jQuery. Libraries are designed to make coding faster and more intuitive and they can be a great productivity aid. You can get a lot more done quicker. There is a downside, however.</p>

<h2>Downside</h2>
<p>If you're doing what the library was intended to help with, great. Slide this panel up, pop open a modal window, scroll to the bottom of the page and highlight that header. Brilliant. The difficulties come when you're either trying to do something the library wasn't intended to do or something nobody's thought of before or you're just plain doing something wrong. If you are fluent in your library of choice but don't know the JavaScript underpinnings, your usual debugging tools can only help you so far. There will come a point where there's an impenetrable black-box where data goes in and something unexpected comes out. Okay, it's probably still data but it's unexpected data.</p>

<p>Don't let this point in the process be the discouragement. This is where the fun bit is.</p>

<h2>Learning to read</h2>
<p>Library authors are very clever groups of people. Often large groups. Reading through the unminified source of a library can be an awesomely educational experience as it's usually the culmination of many years best practice. If you want a nice introduction to some of the cool things in jQuery, for instance, check out these videos from <a href="http://paulirish.com/">Paul Irish</a>:</p>

<ul><li><a href="http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/">http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/</a></li>
<li><a href="http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/">http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/</a></li></ul>

<p>I've dug around in jQuery many, many times to try and figure out why something does or doesn't do what it should or shouldn't. The most detailed investigation was probably <a href="http://thingsinjars.com/post/371/investigating-ies-innerhtml/">Investigating IE's innerHTML</a> during which nothing was solved but I found out some cool stuff.</p>

<h2>Learning to write</h2>
<p>The best way to get your head around libraries is to write your own. Yes, there are literally millions of them (not literally) out there already but you don't need to aim for world dominance, that's not the point of writing your own. Start simply, map the dollar symbol to <code>document.getElementById</code>. Done. You've written a tiny library. </p>

<pre><code>function $(id){ 
    return document.getElementById(id);
}</code></pre>

<p>Now you can add some more stuff. Maybe you could check to see if the thing passed to the $ is already an element or if it's a string. That way, you could be a bit more carefree about how you pass things around.</p>

<pre><code>function $(id){ 
  if(id.nodeType) {
    return id;
  } else {
    return document.getElementById(id);
  }
}</code></pre>

<p>Add in a couple of AJAX methods, some array manipulation and before you know it, you've got a full-blown web development toolkit. </p>

<p>If you're wanting a boilerplate to start your library off, I recommend Adam Sontag's <a href="https://github.com/ajpiano/boilerplate-boilerplate">Boilerplate Boilerplate</a>.</p>

<h2>Here's your Library Card</h2>
<p>By now, you've rooted around in the jQuery undergrowth, dug through some of Moo's AJAX and pulled apart Prototype's string manipulation. You've written your own mini library, gotten a bit frustrated and wished you had a community of several thousand contributors to make it more robust. Now you're ready to start getting irked every time someone on <a href="http://forrst.com">Forrst</a> asks if there's a jQuery plugin for charAt. Enjoy.</p>
<p>This article is modified from a chapter in a book <a href="http://www.phenotypic.co.uk">Andrew</a> and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.</p>      </div>
]]></description>
<pubDate>Thu, 04 Aug 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>A collection of bookmarklets</title>
<link>http://thingsinjars.com/post/415/a-collection-of-bookmarklets/</link>
<guid>http://thingsinjars.com/post/415/a-collection-of-bookmarklets/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-415">
        <p><a href="http://thingsinjars.com/post/415/a-collection-of-bookmarklets/">A collection of bookmarklets</a></p>
<p>Bookmarklets are the handiest little things. In case you don't know (which I'm sure you do), they're small chunks of JS that you store in your browser's Bookmarks or Favourites section which you can launch while looking at any web page. I write bookmarklets for all kinds of different tasks &ndash; navigating quickly around the build monitor at work, filling in tricky forms that my browser autocomplete doesn't handle, etc. </p>

<p>Here are a few of bookmarklets I find extremely useful for web development. To add them to your browser, simply drag the link on the title into your bookmark bar, hold shift down and drag or right-click and 'Add to Favourites', depending on what browser you're in.</p>

<h2><a title="Add Script" href="javascript:(function(){document.body.appendChild(document.createElement('script')).src=prompt('Script to add');})();">Add JS to the page by URL</a></h2>
<p>This will allow you to add any script you like to the current page. This can be particularly useful if you want to add a certain library or plugin to a page to investigate it further.</p>
<pre><code>javascript:(function(){document.body.appendChild(document.createElement('script')).src=prompt('Script to add');})();</code></pre>

<h2><a title="Add jQuery" href="javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://code.jquery.com/jquery-latest.min.js'})();">Add the latest CDN jQuery to the page</a></h2>
<p>A variation on the above bookmarklet, this simply adds the latest version of jQuery. If you want to be able to play with a page and are familiar with jQuery, this will ensure that it is loaded and attached.</p>
<pre><code>javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://code.jquery.com/jquery-latest.min.js'})();</code></pre>

<h2><a title="Add CSS" href="javascript:(function(d){if(d.createStyleSheet)%20{d.createStyleSheet(%20u%20);}%20else%20{var%20css=d.createElement(%27style%27),u=prompt(%27CSS%20to%20add%27);css.setAttribute(%22type%22,%22text/css%22);css.appendChild(document.createTextNode(%22@import%20url(%22+u+%22)%22));d.getElementsByTagName(%22head%22)[0].appendChild(css);}}(document))">Add CSS to the page by URL</a></h2>
<p>Add any stylesheet to the current page with a particular URL. This is handy if you want to demo variations to clients, I find. particularly if you predefine the CSS URL.</p>
<pre><code>javascript:(function(d){if(d.createStyleSheet)%20{d.createStyleSheet(%20u%20);}%20else%20{var%20css=d.createElement(%27style%27),u=prompt(%27CSS%20to%20add%27);css.setAttribute(%22type%22,%22text/css%22);css.appendChild(document.createTextNode(%22@import%20url(%22+u+%22)%22));d.getElementsByTagName(%22head%22)[0].appendChild(css);}}(document))</code></pre>



<h2><a title="Submit to a specific reddit" href="javascript:window.location=%22http://www.reddit.com/r/webdev/submit?url=%22+encodeURIComponent(window.location)+'&title='+encodeURIComponent(document.title);void(0);">Submit this page to the webdev subreddit</a></h2>
<p>This isn't so much a web dev helper, more a general helper. I use this (or a variation thereof) to submit posts to specific <a href="http://www.reddit.com/">reddits</a> with fields prefilled. This bookmarklet defaults to the <a href="http://www.reddit.com/r/webdev/">webdev</a> subreddit.</p>
<pre><code>javascript:window.location=%22http://www.reddit.com/r/webdev/submit?url=%22+encodeURIComponent(window.location)+&#x27;&amp;title=&#x27;+encodeURIComponent(document.title);void(0);</code></pre>

<h2><a href="javascript:(function(){var div = document.createElement('div'); div.innerHTML ='xstyle' +prompt('Style to add')+ '/style';document.body.appendChild(div.lastChild);})();">Add a CSS rule to the page</a></h2>
<p>I can't remember whether I wrote this one or if I found it somewhere. The 'x&lt;style&gt;' is something from the middle of jQuery, though. Anyhow.</p>
<p>This allows you to add a style block directly into the page. This is useful for small CSS injections where the browser's web inspector is unavailable or incapable. Even though it's a single prompt that pops up, there's no reason why you can't past an entire stylesheet in there. I sometimes find myself doing that when I'm previewing designs on a production server.</p>
<pre><code>javascript:(function(){var div = document.createElement(&#x27;div&#x27;); div.innerHTML =&#x27;x&lt;style&gt;&#x27; +prompt(&#x27;Style to add&#x27;)+ &#x27;&lt;/style&gt;&#x27;;document.body.appendChild(div.lastChild);})();</code></pre>      </div>
]]></description>
<pubDate>Mon, 28 May 2012 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Vendor-prefix questions</title>
<link>http://thingsinjars.com/post/414/vendor-prefix-questions/</link>
<guid>http://thingsinjars.com/post/414/vendor-prefix-questions/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-414">
        <p><a href="http://thingsinjars.com/post/414/vendor-prefix-questions/">Vendor-prefix questions</a></p>
<p>There's something that's always niggled me about vendor-specific prefixes on CSS.</p>


<h2>Vendor prefix background</h2>
<p>Just in case you don't know about vendor prefixes, there's a good summary on <a href="http://www.alistapart.com/articles/prefix-or-posthack/">A List Apart</a>.</p>


<p>Best practice dictates that you should <a href="http://www.456bereastreet.com/archive/201009/remember_non-vendor-prefixed_css_3_properties_and_put_them_last/">always include non-prefixed properties last</a>. This is so that when the property does become standard and the browser implements the non vendor-prefix version, it will use the standard rule as it comes later in the stylesheet than the prefixed one. The thing that has been bugging me is the assumption that the agreed standard version produces the same or better results than the prefixed one.</p>

<h2>A convulted and completely made-up example</h2>
<p>Imagine you have a paragraph:</p>
<pre><code rel="html">&lt;p&gt;Made-up text.&lt;/p&gt;</code></pre>
<p>And you want it to have a white border with rounded corners. I'm fully aware you now don't need the vendor prefixes here but bear with me.</p>
<pre><code rel="css">p {
  border:1px solid white;
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  -ms-border-radius:5px;
  -o-border-radius:5px;
  border-radius:5px;
}</code></pre>
<p>In this scenario, the non-prefixed border-radius hasn't been implemented by any browser but you're following best practice so you include the values matching the current specification. Okay, now imagine that for Webkit's implementation of <code>-webkit-border-radius</code>, they decided that the radius value was actually to be divided by two. No problem, you can include the required value for Webkit. Again, not a real example but stick with me.</p>
<pre><code rel="css">p {
  border:1px solid white;
  -webkit-border-radius:10px;
  -moz-border-radius:5px;
  -ms-border-radius:5px;
  -o-border-radius:5px;
  border-radius:5px;
}</code></pre>
<p>You launch the site and send it out into the world.</p>
<p>Six months later, the standard is set, it turns out developers agree on Webkit's implementation. It becomes standard to double your radius value. A month after that, browsers start recognising the non-prefix version of the rule and rendering with the new standard. At this point, webkit, moz, ms and o are all rendering wrong because they are ignoring their vendor-specific implementation and using the non-prefixed standard. Even though webkit currently has the right value, it's being overwritten. If the rules had been included the other way round, they'd still be rendering the same as they were.</p>
<pre><code rel="css">p {
  border:1px solid white;
  border-radius:5px;
  -webkit-border-radius:10px;
  -moz-border-radius:5px;
  -ms-border-radius:5px;
  -o-border-radius:5px;
}</code></pre>
<p>Eventually,support for the prefixed version will be dropped and the browsers will only use the standard but that will be a little way down the line and gives you more time to correct your code or your client's code or wherever the code happens to be. Basically, prefix-last order buys the developer more time to correct any potential issues. I know that by using the vendor-prefixed rules, the developer is implicitly accepting the fact that they are using experimental properties which could change but in this scenario, it is not the prefixed properties that change but the non-prefixed one.</p>

<p>The reason I chose border-radius here is just because it was easier that typing up an example that might actually happen in real-life involving gradients or masks.</p>


<h2>Open to suggestions</h2>
<p>I'm open to any explanation as to why this scenario might never happen or comments on how I've misunderstood something.</p>      </div>
]]></description>
<pubDate>Fri, 29 Jul 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Multi-user pages</title>
<link>http://thingsinjars.com/post/412/multi-user-pages/</link>
<guid>http://thingsinjars.com/post/412/multi-user-pages/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-412">
        <p><a href="http://thingsinjars.com/post/412/multi-user-pages/">Multi-user pages</a></p>
<p>Whenever I'm away from home, my usual stream of random <a href="http://thingsinjars.com/ideas/">ideas</a> tends to become more focused on projects involving sharing. Usually something about creating a connection between people where the interaction point is the Internet. This is what first inspired the now defunct <a href="http://thingsinjars.com/post/135/monkeying-about-with-xul/">MonkeyTV</a> project back in 2007 or <a href="http://noodler.net/">noodler.net</a> in 2008 &ndash; both created while I was living in Tokyo as ways to connect to people back in Edinburgh.</p>

<p>Until the beginning of August, I'm in Berlin finding somewhere to live while Jenni and Oskar are in Edinburgh packing up our flat (although, I'm not entirely sure Oskar is doing much more than drooling over packing boxes). The result of this is that I started to wonder about how to best show Jenni some of the flats I'm looking at remotely. What I figured I wanted was a way for us both to be looking at the same web page and for each of us to be able to point out things to the other. I tidied up my idea and posted it to the <a href="http://byideas.co.uk/i88">Made By Ideas</a> site hoping that someone else would run off and make it so I could focus on apartment hunting.</p>

<p>The inevitable happened, I couldn't let it lie:</p>

<p><a href="javascript:void(things_z=document.body.appendChild(document.createElement('script')));void(things_z.language='javascript');void(things_z.type='text/javascript');void(things_z.src='http://thelab.thingsinjars.com/shared/shared.js');void(things_z.id='things');">Multi-user page</a> (installable bookmarklet).</p>

<p>If you install that bookmarklet by draggin&rsquo; it to your bookmarks bar then launch it anywhere, your cursor position and how far you've scrolled the page will be sent to anyone else viewing the same page who has also launched it. If you launch it on this page just by clicking it just now, you'll see cursors from other people reading this post who've also clicked it.</p>

<h2>Technical</h2>
<p>This is built in <a href="http://nodejs.org/">node.js</a> with <a href="http://socket.io/">socket.io</a>.</p>

<p>It heavily reuses <a href="http://jeffkreeftmeijer.com/2010/experimenting-with-node-js/">Jeff Kreeftmeijer's multiple user cursor experiment</a> but updated to use socket.io v0.7. I also used the socket.io 'rooms' feature to contain clients to a given window.location.href so that it could be launched on any page and interactions would only appear to users on that same page. I also removed the 'speak' feature to simplify things. I'm planning on talking via Skype when I'm using it. In theory, mouse events other than cursor coordinates and scroll could be shared &ndash; keyboard input, clicks, selects. </p>

<p>The day after I built this, <a href="http://www.wait-till-i.com/">Christian Heilmann</a> pointed out <a href="https://twitter.com/#!/codepo8/status/91164622614315010">on twitter</a> a different solution to the same problem. <a href="http://mirror.colorstudy.com/">Browser Mirror</a> uses the same technology (node + websockets) but instead of passing cursor positions, it passes the entire DOM of the page from the instigator's computer to their node relay and then out to any invited viewers. This approach gets round a lot of the problems and is probably a more robust solution, all in all. They also have an integrated chat feature.</p>

<h2>Warning</h2>
<p>The server side is running on a borrowed VPS. It's not even been daemonised using Forever so it might fall over and not come back up. Don't rely on this for anything, just think of it as a point of interest.</p>

<h2>The Code</h2>
<p>I'm not really going to do any further development with it but for interest, here's the node.js server, almost entirely <a href="http://jeffkreeftmeijer.com/2010/experimenting-with-node-js/">Jeff Kreeftmeijer's</a> work but updated for the latest socket.io</p>
<pre><code>var sys = require('sys'),
    http = require('http'),
    io = require('socket.io').listen(8000),
    log = sys.puts;

io.sockets.on('connection', function (socket) {
	socket.on('set location', function (name) {
	    socket.set('location', name, function () { socket.emit('ready'); });
		socket.join(name);
	});
	socket.on('message', function (request) {
		socket.get('location', function (err, name) {
			if(request.action != 'close' && request.action != 'move' && request.action != 'scroll') {
				log('Invalid request:' + "\n" + request);
				return false;
			}
			request.id = socket.id;
			socket.broadcast.to(name).json.send(request);
		});
	});
	socket.on('disconnect', function () {
		socket.broadcast.json.send({'id': socket.id, 'action': 'close'});
	});
});</code></pre>

<p>And here's a bit of the client-side JS that I modified to connect via socket.io v0.7 (again, modified from Jeff Kreeftmeijer's):</p>
<pre><code>
var socket = io.connect('http://yourserver.com', {port: 8000}),
socket.on('connect', function() {
	socket.emit('set location', window.location.href);
	socket.on('message', function(data){
    if(data['action'] == 'close'){
      $('#mouse_'+data['id']).remove();
    } else if(data['action'] == 'move'){
      move(data);
    } else if(data['action'] == 'scroll'){
			clearTimeout(noscrolltimeout);
			disabled = true;
      scroll(data);
			noscrolltimeout = setTimeout('disabled = false;',2000);
    };
  });
});</code></pre>

<p>If you'd like to snoop around the code more, it's all available on the lab: <a href="http://thelab.thingsinjars.com/shared/">Multi-user pages</a></p>

<p>Props to <a href="http://www.phenotypic.co.uk/">Andrew</a> for letting me use his server, by the way. It was enough hassle having to learn node for this little experiment, he saved me from having to build my own.</p>      </div>
]]></description>
<pubDate>Mon, 18 Jul 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Knots</title>
<link>http://thingsinjars.com/post/390/knots/</link>
<guid>http://thingsinjars.com/post/390/knots/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-390">
        <p><a href="http://thingsinjars.com/post/390/knots/">Knots</a></p>
<h2>Game design</h2>
<p>I had an idea around Christmas for a new game design. it was basically to be a single or multi-player game where you would tie knots in a piece of &lsquo;string&rsquo;. The single-player game would focus on discovering new patterns while the multi-player one would be a time-based challenge where each would tie a knot, pass it over to their opponent and the first to untie it would win.</p>

<p>I built a basic prototype and had some fun inventing a few interesting knots (my favourite being &lsquo;Yoda&rsquo;) but didn't get round to doing anything with it. As I'm tidying up all my projects before immigrating to Germany, I figured I should just go ahead and put this out into the world.</p>

<p><a href="http://apps.angryrobotzombie.com/knot/">Knot v0.1</a></p>

<h2>Slightly technical bit</h2>
<p>The system is built using an invisible 3x3 grid and 4 quadratic curves. The curves' start, control and end points are the centre of a tile. When you move a tile, it basically swaps position with the tile nearest where you drop it. This can also be done with multiple tiles simultaneously if you're on a multi-touch device. You can see the tiles if you enable debug mode. You can also switch between the two colour schemes it has at the moment.</p>


Yoda in Knot form
<img src="http://thingsinjars.com/uploaded/images/yoda.png" alt="Yoda Knot">


<p>The only addition I've made to it since Christmas was to add on a system to allow players to save knots back into the system. I've only built in 22 patterns so if you make a nice, interesting or funny one, give it a recognisable name (nothing too rude, please) and save it, it will then be available to everybody who plays with it. You can also set whether the pattern is to count as &lsquo;matched&rsquo; when rotated 90&deg;, 180&deg;, flipped vertically or flipped horizontally. Calculating the isomorphisms (when two knots look the same to the viewer but aren't necessarily the same to the computer) was probably the trickiest bit of the system.</p>

<h2>Go, make.</h2>
<p>If you're interested in taking the idea further, <a href="https://github.com/thingsinjars/Knot">grab the code from GitHub</a> and make something from it. The usual rules apply, if you make something from it that makes you a huge tonne of neverending cash, a credit would be nice and, if you felt generous, you could always buy me a larger TV.</p>

<p><a href="http://apps.angryrobotzombie.com/knot/">Knot v0.1</a></p>
      </div>
]]></description>
<pubDate>Mon, 27 Jun 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Instant art</title>
<link>http://thingsinjars.com/post/381/instant-art/</link>
<guid>http://thingsinjars.com/post/381/instant-art/</guid>
<description><![CDATA[
        <div class="teaser " id="teaser-381">
        <p><a href="http://thingsinjars.com/post/381/instant-art/">Instant art</a></p>
I love making silly little digital toys. If I were more confident at talking waffle, I'd call them art and get a government grant to pursue the possibilities presented in projects integrating off and online expression and interaction and blah, blah, blah.

Anyway.

I took my '<a href="http://thingsinjars.com/post/294/art-maker-1k/">Automatic Tumblr Art Maker</a>' from last year and combined it with the hot new thing in town – <a href="http://instagr.am/">Instagram</a> – to make some kind of comment about the inherent nature of technology to remove the individuality from a composition and to put another barrier between the intention and reception. Or something. I dunno. It randomly generates a pseudo-meaningful statement and puts it on top of a randomly selected recent Instagram photo. It makes a new one every 15 seconds or you can click to generate one if you prefer your ironic art on demand. 

I've also added a couple of nice little extras to it: the tweet button in the bottom right will let you share a link to the exact combination of image and statement you're looking at so if you find a particularly poignant/ironic/idiotic one, you can share it. Also, on the off-chance you fancy using it as a screensaver, making it fullscreen will hide that tweet button so as not to get in the way of The Art.

Go, make ironic <a href="http://thelab.thingsinjars.com/insta-art.html">Insta-art</a>.      </div>
]]></description>
<pubDate>Mon, 30 May 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Investigating IE's innerHTML</title>
<link>http://thingsinjars.com/post/371/investigating-ies-innerhtml/</link>
<guid>http://thingsinjars.com/post/371/investigating-ies-innerhtml/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-371">
        <p><a href="http://thingsinjars.com/post/371/investigating-ies-innerhtml/">Investigating IE's innerHTML</a></p>
<p>Be warned, this is a long and quite techy post that rambles a bit. It's about JS, <a href="http://jquery.com/" title="jQuery: The Write Less, Do More, JavaScript Library">jQuery</a>, IE and XML namespaces. Be careful.</p>
<p>I'm currently working on a tool which uses JS to parse an XML document and output it as JSON. Straightforward enough, you'd think. The issue I'm fighting against crops up when the XML tags have an arbitrary namespace. True enough, some of the files I'll be processing have this namespace defined at the top of the document but the tool has to be robust enough to cope when they don't.</p>
<p>To cut a long story short, IE6, IE7 and IE8 have an interesting attitude to innerHTML when the tags you are trying to insert have a namespace. IE9 seems to do the job as you'd expect. I've created some <a href="http://jsfiddle.net">jsFiddle</a> pages which try and identify the issues. They both use <a href="http://docs.jquery.com/Qunit" title="QUnit - jQuery JavaScript Library">QUnit</a> and the test code is included below.</p>
<h2>createElement nodeName vs get(0).nodeName</h2>
<p><a href="http://jsfiddle.net/thingsinjars/j4xJG/">View this on jsFiddle.net</a></p>
<p>I started off using jQuery to help identify this as the tool uses jQuery for the XML heavy-lifting. The two tests in this demo create elements in two different ways. First, we create the element using document.createElement and grab the nodeName then we use jQuery's constructor and use get(0) to grab the bare DOM element's nodeName. Also, in this first set of tests, we're creating non-standard elements.</p>
<pre><code class="prettyprint lang-js">
test("Compare elements without namespace", function() {
 var element1, element2;

 element1 = document.createElement('spud').nodeName;
 element2 = $('&lt;spud/&gt;').get(0).nodeName;

 equals(element1, element2, "We expect these to match");
});
</code></pre>

<p>The code above runs fine everywhere – IE, FireFox, Opera, Chrome, etc. etc. Good.</p>

<pre><code class="prettyprint lang-js">
test("Compare elements with namespace", function() {
 var element1, element2;

 element1 = document.createElement('a:spud').nodeName;
 element2 = $('&lt;a:spud/&gt;').get(0).nodeName;

 equals(element1, element2, "We expect these to match");
});
</code></pre>

<p>This runs fine in non-IE browsers, they all report the nodeName as <code>'a:spud'</code>. IE now reports the nodeName as <code>'spud'</code>. Ah. I dug through the jQuery source, tracking down the bare roots of the constructor and eventually figured out that just looking at the element itself isn't going to provide any clues. The bit that does the actual string-to-elements work (somewhere around <a href="https://github.com/jquery/jquery/blob/master/src/manipulation.js#L587">line 5619 in jQuery 1.5.2</a>) creates a container div then injects the (slightly modified) code as innerHTML. The issue must be in IE's interpretation of innerHTML, I thought to myself. And then to you by writing it here.</p>

<h2>.innerHTML aside</h2>
<h3>or ‘jQuery is clever’</h3>
<p>Before we continue with this long and, ultimately, unnecessary investigation into namespaces, I have to take a small diversion to cover some smart stuff jQuery does. One thing in particular, in fact. Around that line I mentioned earlier (5619-ish), an extra bit of text is inserted into the innerHTML to cope with IE's oddity. If you are trying to create a non-standard element using innerHTML, IE will not complain but also just do pretty much nothing at all:</p>
<pre><code class="prettyprint lang-js">        var div = document.createElement('div');
        div.innerHTML = '&lt;spud&gt;&lt;/spud&gt;';
        alert(div.innerHTML);
</code></pre>
<p>The above code will alert <code>'&lt;spud&gt;&lt;/spud&gt;'</code> in most browsers but <code>''</code> in IE. What jQuery does is firstly wrap your element in an extra <code>&lt;div&gt;&lt;/div&gt;</code> (producing <code>'&lt;DIV&gt;&lt;/DIV&gt;'</code>) then prepends the word 'div' to that. The innerHTML reported by IE is now <code>'div&lt;DIV&gt;&lt;SPUD>&lt;/SPUD&gt;&lt;/DIV&gt;'</code>! There it is! Next, the extra gubbins is removed by calling .lastChild and you're left with <code>innerHTML = '&lt;SPUD&gt;&lt;/SPUD&gt;'</code>. That's pretty darned clever.</p>

<h2>.innerHTML vs document.appendChild</h2>
<p><a href="http://jsfiddle.net/thingsinjars/4ZsKU/">View this on jsFiddle.net</a></p>
<p>Back on track. Armed with this little trick, we can reliably test innerHTML in IE using non-standard elements.</p>

<pre><code class="prettyprint lang-js">
module("Known elements (span)");
 test("Compare elements without namespace", function() {
  var div1, div2;

  div1 = document.createElement('div');
  div1.innerHTML = '&lt;span&gt;&lt;/span&gt;';

  div2 = document.createElement('div');
  div2.appendChild(document.createElement('span'));

  equals(div1.innerHTML.toLowerCase(), div2.innerHTML.toLowerCase(),
     "We expect these to match");
 });

 test("Compare elements with namespace", function() {
  var div1, div2;

  div1 = document.createElement('div');
  div1.innerHTML = '&lt;u:span&gt;&lt;/u:span&gt;';

  div2 = document.createElement('div');
  div2.appendChild(document.createElement('u:span'));

  equals(div1.innerHTML.toLowerCase(), div2.innerHTML.toLowerCase(),
     "We expect these to match");
 });
</code></pre>

<p>The first test in this pair runs fine everywhere exactly as we'd hope and expect. The second fails miserably in IE. Let us quickly run the same test with unknown elements just to make sure we're identifying the right problem:</p>

<pre><code class="prettyprint lang-js">module("Unknown elements (spud)");
 test("Compare elements without namespace", function() {
  var div1, div2;

  div1 = document.createElement('div');
  div1.innerHTML = 'div&lt;div&gt;' + '&lt;spud&gt;&lt;/spud&gt;' + '&lt;/div&gt;';
  div1 = div1.lastChild;

  div2 = document.createElement('div');
  div2.appendChild(document.createElement('spud'));

  equals(div1.innerHTML.toLowerCase(), div2.innerHTML.toLowerCase(),
     "We expect these to match");
 });
 test("Compare elements with namespace", function() {
  var div1, div2;

  div1 = document.createElement('div');
  div1.innerHTML = 'div&lt;div&gt;' + '&lt;u:spud&gt;&lt;/u:spud&gt;' + '&lt;/div&gt;';
  div1 = div1.lastChild;

  div2 = document.createElement('div');
  div2.appendChild(document.createElement('u:spud'));

  equals(div1.innerHTML.toLowerCase(), div2.innerHTML.toLowerCase(),
     "We expect these to match");
 });
</code></pre>

<p>As before, the first test in this pair works fine, the second fails. Cool. Or not. Either way, you can now see that it doesn't really matter whether the elements are standard or custom and that little diversion we took earlier really was unnecessary. Still, you know more now about some of the cleverness in jQuery than you did before.</p>

<p>It turns out the reason IE reports the nodeNames as the non-namespaced ones is because it has been busy behind the scenes and added an extra XML namespace prefix into our current context. The innerHTML of the div we filled up using innerHTML has been modified to:</p>

<pre><code class="prettyprint lang-js">  &lt;?xml:namespace prefix = u /&gt;
  &lt;u:span&gt;&lt;/u:span&gt;
</code></pre>

<p>Where'd that namespace declaration come from?! Goshdarnit, IE. From its point of view, within that little context, <code>u:span</code> is equivalent to <code>span</code></p>

<h2>The most stripped-down example</h2>
<p><a href="http://jsfiddle.net/thingsinjars/pfQbG/" title="Checking validity of innerHTML">View this on jsFiddle</a></p>
<p>Seriously, it does not get more fundamental than this.</p>
<pre><code class="prettyprint lang-js">element = document.createElement('div');
testHTML = '&lt;div&gt;&lt;/div&gt;';
element.innerHTML = testHTML;
element.innerHTML.toLowerCase() == testHTML.toLowerCase() 
</code></pre>
<p>The last line there is true for all browsers.</p>
<pre><code class="prettyprint lang-js">element = document.createElement('div');
testHTML = '&lt;a:div&gt;&lt;/a:div&gt;';
element.innerHTML = testHTML;
element.innerHTML.toLowerCase() == testHTML.toLowerCase() 
</code></pre>
<p>The last line there is true for all browsers <em>except IE 6, 7 and 8!</em></p>

<h2>In conclusion?</h2>
<p>Ultimately, there are no winners here. Identifying the problem is quite different from fixing it. I've added a note to the relevant <a href="http://bugs.jquery.com/ticket/4208">jQuery bug</a> in the tracker but it's not so much a bug in jQuery as a humorous IE quirk. There's some talk of refactoring the <a href="http://api.jquery.com/find/" title=".find() &#8211; jQuery API">.find() method</a> to handle more complicated tagnames so this might get picked up then. The fix will probably be something along the lines of checking the outcome of the innerHTML doesn't have an unexpected namespace declaration when the selector has a colon in it:</p>
<pre><code class="prettyprint lang-js">div.replace( /]*>/g, '' )</code></pre>
<p>I'd submit the patch myself but I'm having difficulty getting unmodified jQuery to build on any of my machines without failing most of the QUnit tests. I've probably typed something wrong.</p>      </div>
]]></description>
<pubDate>Fri, 01 Apr 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>8 bit alpha</title>
<link>http://thingsinjars.com/post/368/8-bit-alpha/</link>
<guid>http://thingsinjars.com/post/368/8-bit-alpha/</guid>
<description><![CDATA[
        <div class="teaser " id="teaser-368">
        <p><a href="http://thingsinjars.com/post/368/8-bit-alpha/">8 bit alpha</a></p>
Another week, another launch. I really need to find a cure for whatever illness I have that results in compulsion to built stuff. Maybe there's a Builders Anonymous group where you can go for support in coming to terms with the fact that you don't always <em>have to</em> solve the problem yourself. Learn to accept that sometimes things are just the way they are.

Pshaw!

A few days ago, I read <a href="http://calendar.perfplanet.com/2010/png-that-works/">this article</a> by <a href="http://pornel.net/">Kornel Lesiński</a>. It describes the curious and interesting ways of PNGs, particularly highlighting the fact that the 8-bit PNG with an embedded alpha channel needs a lot more love than it gets. It gives you the small file sizes you get from 8-bit PNGs (resulting from the maximum 255 colour palette) but also the benefits of a full partial transparency alpha channel unlike GIFs or standard 8-bit PNGs in which pixels are on or off, nothing in between. The reason this file type is ignored is because the most common web graphic creation application in the world (Adobe Photoshop) doesn't support them. At least not yet. You need Adobe Fireworks or some other application to convert your 24-bit alpha channel images.

After a quick search turned up nothing but instructions on how to enable command-line convertion on a Linux server, I figured this would be a handy web service. Drag, Drop, Download, Done. This also gave me an excuse to play with some <a href="https://developer.mozilla.org/en/using_files_from_web_applications">File API</a> stuff. In the end, I decided to use a <a href="https://github.com/pangratz/dnd-file-upload">jQuery plugin</a> because there was a greater chance that it had been tested and bugfixed than my own script.

<h2><a href="http://www.8bitalpha.com">8-bit alpha</a></h2>

With a name like that, I had to go for a retro theme. I even created a nice <a href="http://www.8bitalpha.com/images/spinner.gif" title="eight bit indicator image">8-bit spinner</a>.

If you have a use for the service, <a href="http://twitter.com/thingsinjars">let me know</a>, if you want to learn how it works, <a href="https://github.com/thingsinjars/8bitalpha">browse the source</a>. If you want to popularise the phrase “Drag, Drop, Download, Done” for this kind of simple web application, do that too.      </div>
]]></description>
<pubDate>Fri, 25 Mar 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Scoped Style</title>
<link>http://thingsinjars.com/post/360/scoped-style/</link>
<guid>http://thingsinjars.com/post/360/scoped-style/</guid>
<description><![CDATA[
        <div class="teaser " id="teaser-360">
        <p><a href="http://thingsinjars.com/post/360/scoped-style/">Scoped Style</a></p>
I couldn't let it lie. The nifty JavaScript from <a href="http://thingsinjars.com/post/359/css-scoped/">the previous post</a> was all well and good but I had to have a go at jQuery plugin-ifying it. It has been Enpluginated.

Your options now are simple:
<ol>
<li>Have a look at <a href="http://thelab.thingsinjars.com/scoped/index.html">a demo</a></li>
<li><a href="https://github.com/thingsinjars/jQuery-Scoped-CSS-plugin">Check out the source on GitHub</a></li>
<li><a href="https://github.com/thingsinjars/jQuery-Scoped-CSS-plugin/archives/master">Download it</a> and start scoping some styles.</li>
</ol>

If you still have no idea what I'm talking about, you can <a href="http://www.w3.org/TR/html5/semantics.html#the-style-element">read about the attribute</a>. There are still a couple of bugs when the scoped blocks are deeply nested within other scoped areas so I'm hoping someone with a keen sense of how to straighten out Webkit oddness can help. When browsers don't implement functionality, it's a bit tricky to guess what they'd mean.

Aside from that, it's cross-browser (IE7+) compatible and ready to use. I'm interested to know if anyone finds it useful or finds any odd combinations of styles that don't scope nicely.      </div>
]]></description>
<pubDate>Sun, 30 Jan 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>CSS Scoped</title>
<link>http://thingsinjars.com/post/359/css-scoped/</link>
<guid>http://thingsinjars.com/post/359/css-scoped/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-359">
        <p><a href="http://thingsinjars.com/post/359/css-scoped/">CSS Scoped</a></p>
<p>Update: <a href="http://thingsinjars.com/post/360/scoped-style/">Bam! Plugin'd</a></p>
<p>One of the things in HTML5 that caught my eye a while back was the new 'scoped' attribute for style tags. The idea of it is that you can include a style element mid-document, mark it as scoped and its declarations will only apply to the style elements parent element and its child elements. The styles won't affect anything outside this. The biggest problem with bringing in this attribute is that it's not backwards compatible. If you include a style block mid-page, its declarations will be applied to ever element whose selector matches, inside or outside scope. It is anti-progressively enhancable. This means that designers and developers can't start using it until there's enough support. What we need is another of those JS tricks to make it usable.</p>

<p>Possibly the idea of having a style block dropped into the middle of a semantic document strikes you as a distasteful but thinking practically, this could make CMS workflows a bit easier and keep global stylesheets clean of lots of one-off specific styles. For example, <a href="http://thingsinjars.com/post/334/testing-css3-stuff/">this post</a> describing striped CSS backgrounds could have benefited from having the demo directly within the body of the post but, without going into the backend to add an extra id, this could have messed up the layouts for all other posts.</p>

<p>My first attempt at solving this problem with JS involved generating a unique class, adding it to the parent element and then parsing the style blocks using <a href="http://www.glazman.org/JSCSSP/">JSCSSP</a> so that I could rewrite them with the new class to add specificity. This approach only worked for the most basic declarations, unfortunately. The parser worked perfectly but there's a lot of detail in CSS specificity that mean this would be a much larger problem than I thought.</p>

<p>My second attempt involved:</p>
<ol>
<li>Allowing the style blocks to affect everything on the page (at which point, the elements in-scope look right, those out-of-scope look wrong)</li>
<li>Using JS to read the current computed styles of each element in-scope and copy them to a temporary array</li>
<li>Emptying out the scoped style element (in-scope look wrong, out-of-scope looks right)</li>
<li>Copying the styles back from the temporary array onto each element</li>
</ol>

<p>The first couple of versions only work in webkit, the latest (below) works in mozilla, too.</p>

<p>This <a href="http://thelab.thingsinjars.com/scoped/index-single.html">worked great</a> unless you had <a href="http://thelab.thingsinjars.com/scoped/index-multiple.html">more than one</a> scoped block – step 1 allowed scoped styles to affect each other.</p>

<p>The current attempt involves temporarily emptying all other scoped styles before taking the computed styles from a block. I'm now just thinking that this method might not work if you have multiple scoped blocks within the same context. Oh well, there's something to fix in the future.</p>

<p><a href="http://thelab.thingsinjars.com/scoped/index-js.html">This is where I'm at just now</a>.</p>

<p>Yes, it's a mess, yes the JS is scrappy and yes, it doesn't currently work in IE but I'll get round to that next. It took long enough to get it working in Firefox as there's no simple way to convert a ComputedCSSStyleDeclaration to a string in Mozilla unlike Webkit's implementation of cssText or IE's currentStyle. I might even make it into one of those new-fangled jQuery plugins everyone's using these days.</p>
      </div>
]]></description>
<pubDate>Fri, 28 Jan 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>jQTouch Calendar Extension</title>
<link>http://thingsinjars.com/post/357/jqtouch-calendar-extension/</link>
<guid>http://thingsinjars.com/post/357/jqtouch-calendar-extension/</guid>
<description><![CDATA[
        <div class="teaser " id="teaser-357">
        <p><a href="http://thingsinjars.com/post/357/jqtouch-calendar-extension/">jQTouch Calendar Extension</a></p>
I needed to build an offline calendar in jQTouch for a project and found this particularly nice-looking <a href="http://code.google.com/p/jqtouch-ical/">jQTouch iCal project</a> by <a href="http://www.balexandre.com/">Bruno Alexandre</a>. Unfortunately, it required a server connection.

A day later and I've pulled the thing apart, refactored and rebuilt into a shiny jQTouch extension (still using the original project's CSS). It's built for Mobile Safari but still looks good in other webkits.

<a href="http://thelab.thingsinjars.com/jqt.calendar/">View a demo</a>

Grab the code from <a href="https://github.com/thingsinjars/jQTouch-Calendar">the GitHub repository</a>
      </div>
]]></description>
<pubDate>Wed, 26 Jan 2011 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Testing CSS3 stuff</title>
<link>http://thingsinjars.com/post/334/testing-css3-stuff/</link>
<guid>http://thingsinjars.com/post/334/testing-css3-stuff/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-334">
        <p><a href="http://thingsinjars.com/post/334/testing-css3-stuff/">Testing CSS3 stuff</a></p>
<p>You may have seen Google's 'Watch this space' advertising appearing all over the place. They have quite eye-catching diagonally striped backgrounds in various colours. A couple of days ago, I was wondering how easy it would be to recreate this in CSS without images. Unfortunately, the state of CSS 3 is such that some things work wonderfully, some just plain don't (scoped attribute, I'm looking at you). The following code relies on vendor extensions and so, unless you're willing to tend it and correct it after the spec is finalised, don't use this on a production server.</p>
<p>The most obvious thing to notice from the following code, though, is the competing syntax for the repeating linear gradient style. Mozilla have separated it into a distinct style (<code>-moz-repeating-linear-gradient</code>) while Webkit have built it as an option to their general gradient style (<code>-webkit-gradient</code>).</p>
<pre><code class="prettyprint">body {
	background-image: -moz-repeating-linear-gradient(
		-45deg,
		transparent,
		transparent       25%,
		rgba(0,0,0,0.15)  25%,
		rgba(0,0,0,0.15)  50%,
		transparent       50%,
		transparent       75%,
		rgba(0,0,0,0.15)  75%,
		rgba(0,0,0,0.15)
	);
	background-image: -webkit-gradient(
		linear,
		0% 0%,
		100% 100%,
		from(transparent),
		color-stop(0.25, transparent),
		color-stop(0.25, rgba(0,0,0,0.15)),
		color-stop(0.50, rgba(0,0,0,0.15)),
		color-stop(0.50, transparent),
		color-stop(0.75, transparent),
		color-stop(0.75, rgba(0,0,0,0.15)),
		to(rgba(0,0,0,0.15))
	);
}</code></pre>
<p>To get a better idea of what this does, view source on <a href="http://thelab.thingsinjars.com/watch-these-stripes.html">this demo page</a>. This includes a button to change the class on the body (using JS) which simply changes the background colour – the stripes are semi-transparent on top of that. Remember, due to the vendor prefixes, this only works in -moz or -webkit browsers.</p>
<p>It's supposed to look like this:</p>
<ul class="gallery"><li><a href="http://thingsinjars.com/uploaded/images/striped.png" rel="lightbox"><img src="http://thingsinjars.com/uploaded/images/thumbs/striped.png" /></a></li></ul>      </div>
]]></description>
<pubDate>Wed, 08 Dec 2010 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Maze 1k</title>
<link>http://thingsinjars.com/post/296/maze-1k/</link>
<guid>http://thingsinjars.com/post/296/maze-1k/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-296">
        <p><a href="http://thingsinjars.com/post/296/maze-1k/">Maze 1k</a></p>
<ul><li><a href="http://thingsinjars.com/widgets/js1k3.html">Random perfect maze generation, solution and rendering in 1011 bytes</a></li></ul>

<p>Okay, this is the last one for a while. Really.</p>

<p>Unlike my previous 1k JavaScript demos, I really had to struggle to get this one into the 1024 byte limit. I'd already done all the magnification and optimization techniques I knew of so I had to bring in some things which were new to me from <a href="http://qfox.nl/notes/111">qfox.nl</a> and <a href="http://benalman.com/news/2010/08/organ1k-js1k-contest-entry/">Ben Alman</a> and a few other places. This, combined with some major code refactoring, brought it down from 1.5k to just under 1. In the process, all possible readability was lost so here's a quick run through what it does and why.</p>

<h2>First up, a bunch of declarations.</h2>

<p>These are the colours used to draw the maze. Note, I used the shortest possible way to write each colour (<code class="prettyprint">red</code> instead of <code class="prettyprint">#F00</code>, <code class="prettyprint">99</code> instead of <code class="prettyprint">100</code>). The value stored in the maze array (mentioned later) refers not only to the type of block it is but also to the index of the colour in this array, saving some space.</p>
<pre><code class="prettyprint">u = ["#eff", "red", "#122", "rgba(99,255,99,.1)", "#ff0"],</code></pre>

<p>This is used for the number of blocks wide and high the maze is, the number of pixels per block, the size of the canvas and the redraw interval. Thanks to <a href="http://github.com/cowboy/js1k-organ1k/blob/master/organ1k.js">Ben Alman</a> for pointing out in his article how to best use a constant.</p>
<pre><code class="prettyprint"> c = 21,</code></pre>

<p>Here is the reference to the canvas. Mid-minification, I did have a bunch of function shortcuts here - <code class="prettyprint">r=Math.random</code>, for instance - but I ended up refactoring them out of the code.</p>
<pre><code class="prettyprint">m = document.body.children[0];</code></pre>

<p>For most of the time when working on this, the maze was wider than it was high because I thought that made a more interesting maze. When it came down to it, though, it was really a matter of bytesaving to drop the distinct values for width and height. After that, we grab the canvas context so we can actually draw stuff.</p>
<pre><code class="prettyprint">m.width = m.height = c * c;
h = m.getContext("2d");</code></pre>

<h2>The drawing function</h2>
<p>The generation and solution algorithm is quite nice and all but without this to draw it on the screen, it's really just a mathematical curio. This takes a colour, x and y and draws a square.</p>

<pre><code class="prettyprint">l = function (i, e, f) {
  h.fillStyle = i;
  h.fillRect(e * c, f * c, c, c)
};</code></pre>

<h2>Designing a perfect maze</h2>

<p>"You've got 1 minute to design a maze it takes 2 minutes to solve."<br />- Cobb, Inception.</p>

<p>Apologies for the unnecessary Inception quote. It's really not relevant.</p>

<p>Algorithmically, this is a fairly standard <a href="http://en.wikipedia.org/wiki/Maze_solving_algorithm">perfect maze</a> generator. It starts at one point and randomly picks a direction to walk in then it stops picks another random direction and repeats. If it can't move, it goes back to the last choice it made and picks a different direction, if there are no more directions, all blocks have been covered and we're done. In a perfect maze, there is a path (and only one path) between any two randomly chosen points so we can make the maze then denote the top left as the start and the bottom right as the end. This particular algorithm takes 2 steps in every direction instead of 1 so that we effectively carve out rooms and leave walls. You can take single steps but it's actually more of a hassle.</p>

<p>For more on how this kind of maze-generation works, check out this article on <a href="http://www.emanueleferonato.com/2008/12/06/perfect-maze-generation-tile-based-version/">Tile-based maze generation</a>.</p>

<h3>Blank canvas</h3>
<p>This is a standard loop to create a blank maze full of walls with no corridors. The <code class="prettyprint">2</code> represents the 'wall' block type and the colour <code class="prettyprint">#122</code>. The only really odd thing about this is the code <code class="prettyprint">f-->0</code> which is not to be read 'as f tends to zero' but is instead 'decrement f by 1, is it greater than zero?'</p>
<pre><code class="prettyprint">g = function () {
  v = [];  //our stack of moves taken so we can retrace our steps.
  for (i = [], e = c; e-- > 0;) {
    i[e] = [];
    for (f = c; f-- > 0;) i[e][f] = 2
  }</code></pre>

<p>By this point, we have a two-dimensional JavaScript array filled with 2s</p>

<h3>Putting things in</h3>
<pre><code class="prettyprint">  f = e = 1;    // our starting point, top left.
  i[e][f] = 0; // us, the zippy yellow thing</code></pre>

<h3>Carving out the walls</h3>
<p>This is our first proper <em>abuse</em> of the standard for-loop convention. You don't need to use the three-part structure for 'initialize variable; until variable reaches a different value; change value of variable'. It's 'do something before we start; keep going until this is false; do this after every repetition' so here we push our first move onto the stack then repeat the loop while there's still a move left on the stack.</p>
<pre><code class="prettyprint">  for (v.push([e, f]); v.length;) {</code></pre>

<p>P here is the list of potential moves from our current position. For every block, we have a look to see what neighbours are available then concatenate that cardinal direction onto the strong of potential moves. This was originally done with bitwise flags (the proper way) but it ended up longer. It's also a bit of a nasty hack to set p to be 0 instead of "" but, again, it's all about the bytes.</p>
<pre><code class="prettyprint">  p = 0;</code></pre>

<h3>Can we walk this way?</h3>
<p>These are all basically the same and mean 'if we aren't at the edge of the board and we're looking at a wall, we can tunnel into it.'.</p>
<pre><code class="prettyprint"> if (e < 18 && i[e + 2][f] == 2) p += "S"
 if (e >= 2 && i[e - 2][f] == 2) p += "N";
 if (f >= 2 && i[e][f - 2] == 2) p += "W";
 if (i[e][f + 2] == 2) p += "E";

 if (p) { //    If we've found at least one move
  switch (p[~~ (Math.random() * p.length)]) { // randomly pick one</code></pre>
<p>If there was anything to note from that last chunk, it would be that the operator <code class="prettyprint">~~</code> can be used to floor the current value. It will return the integer below thye current value.</p>

<h3>Take two steps</h3>
<p>This is a nice little hack. Because we're moving two spaces, we need to set the block we're on and the next one to be 0 (empty). This takes advantage of the right-associative unary operator 'decrement before' and the right associativity of assignment operators. It subtracts 1 from e (to place us on the square immediately above) then sets that to equal 0 then subtracts 1 from the new e (to put us on the next square up again) and sets that to equal the same as the previous operation, i.e. 0.</p>
<pre><code class="prettyprint">  case "N":
      i[--e][f] = i[--e][f] = 0;
      break;</code></pre>

<h3>Do the same for s, w and e</h3>
<pre><code class="prettyprint">    case "S":
      i[++e][f] = i[++e][f] = 0;
      break;
    case "W":
      i[e][--f] = i[e][--f] = 0;
      break;
    case "E":
      i[e][++f] = i[e][++f] = 0
    }</code></pre>

<p>Whichever move we chose, stick that onto the stack.</p>
<pre><code class="prettyprint">    v.push([e, f])</code></pre>

<h3>If there were no possible moves, backtrack</h3>
<pre><code class="prettyprint">  } else {
    b = v.pop(); //take the top move off the stack
    e = b[0]; // move there
    f = b[1]
  }
 }</code></pre>

<h3>End at the end</h3>
<p>At the very end, set the bottom right block to be the goal then return the completed maze.</p>
<pre><code class="prettyprint">  i[19][19] = 1;
  return i
};</code></pre>

<h2>Solver</h2>
<p>This is the solving function. Initially, it used the same algorithm as the generation function, namely 'collect the possible moves, randomly choose one' but this took too much space. So instead it looks for spaces north, then south, then west, then east. It follows the first one it finds.</p>
<pre><code class="prettyprint">s = function () {</code></pre>

<p>Set the block type of the previous block as 'visited' (rgba(99,255,99,.1) the alpha value makes the yellow fade to green).</p>
<pre><code class="prettyprint">  n[o][y] = 3;</code></pre>

<h3>A bit of ternary background</h3>
<p>This next bit looks worse than it is. It's the ternary operator nested several times. The ternary operator is a shorthand way of writing:</p>
<pre><code class="prettyprint">if ( statement A is true ) {
  Do Action 1
} else {
  Do Action 2
}</code></pre>

<p>In shorthand, this is written as:</p>

<pre><code class="prettyprint">Statement A ? Action 1 : Action 2;</code></pre>

<p>In this, however, I've replace Action 2 with another ternary operator:</p>

<pre><code class="prettyprint">Statement A ? Action 1 : ( Statement B ? Action 2 : Action 3 );</code></pre>

<p>And again, and again. Each time, it checks a direction, if it's empty, mark it as visited and push the move onto our stack.</p>
<pre><code class="prettyprint">(n[o + 1][y] < 2) ?
  (n[++o][y] = 0, v.push([o, y])) :
    (n[o - 1][y] < 2) ?
      (n[--o][y] = 0, v.push([o, y])) :
        (n[o][y - 1] < 2) ?
          (n[o][--y] = 0, v.push([o, y])) :
            (n[o][y + 1] < 2) ?
              (n[o][++y] = 0, v.push([o, y])) :</code></pre>

<h3>If none of the neighbours are available, backtrack</h3>
<pre><code class="prettyprint">                (b = v.pop(), o = b[0], y = b[1]);</code></pre>

<h3>Show where we are</h3>
<p>Finally, set our new current block to be yellow</p>
<pre><code class="prettyprint">  n[o][y] = 4;</code></pre>

<h3>Are we there yet?</h3>
<p>If we are at the bottom right square, we've completed the maze</p>
<pre><code class="prettyprint">  if (o == 19 && y == 19) {
  n = g();    //Generate a new maze
  o = y = 1; //Move us back to the top right
  s()     //Solve again</code></pre>

<p>If we haven't completed the maze, call the solve function again to take the next step but delay it for 21 milliseconds so that it looks pretty and doesn't zip around the maze too fast.</p>
<pre><code class="prettyprint">  } else setTimeout(s, c);</code></pre>

<h3>Paint it black. And green. And yellow.</h3>
<p>This is the code to render the maze. It starts at the top and works through the whole maze array calling the painting function with each block type (a.k.a. colour) and position.</p>
<pre><code class="prettyprint">    for (d in n) for (a in n[d]) l(u[n[d][a]], a, d)
  };</code></pre>

<h2>Start</h2>
<p>This is the initial call to solve the maze. The function s doesn't take any arguments but by passing these in, they get called before s and save a byte that would have been used if they had been on a line themselves.</p>
<pre><code class="prettyprint">s(n = g(), o = y = 1)</code></pre>

<h2>Done</h2>
<p>This little demo isn't as visually appealing as the <a href="http://thingsinjars.com/post/294/art-maker-1k/">Art Maker 1k</a> or as interactive as the <a href="http://thingsinjars.com/post/292/elementally-my-dear-javascript/">Spinny Circles 1k</a> but it is quite nice mathematically. There are now some astounding pieces of work in the <a href="http://js1k.com">JS1K demo competition</a>, though. I do recommend spending a good hour playing about with them all. Don't, however, open a bunch of them in the background at the same time. Small code isn't necessarily memory-efficient and you could quite easily grind your computer to a standstill.</p>      </div>
]]></description>
<pubDate>Thu, 19 Aug 2010 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Art Maker 1K</title>
<link>http://thingsinjars.com/post/294/art-maker-1k/</link>
<guid>http://thingsinjars.com/post/294/art-maker-1k/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-294">
        <p><a href="http://thingsinjars.com/post/294/art-maker-1k/">Art Maker 1K</a></p>
<p>Even though the rules for <a href="http://js1k.com">js1k</a> only let me make one submission, I couldn't stop myself making another. This one is inspired by those pseudo-romantic pictures that you get <a href="http://fueledbyphotos.com/">all</a> <a href="http://icanread.tumblr.com/">over</a> <a href="http://everythingsright.com/">tumblr</a> that get reblogged endlessly (actually, it was inspired by the blog <a href="http://thatisntart.com/">That Isn't Art</a> by someone with the same opinion as myself).</p>

<p>It randomly creates a sentence, adds some softly-moving almost bokeh coloured-circles and look, I made an art! Wait for the sentence to change or click (or touch) to change it yourself.</p>

<p><a href="http://thingsinjars.com/widgets/js1k2.html">Art Maker 1k</a></p>

<p>And of course, don't forget the original <a href="http://thingsinjars.com/widgets/js1k.html">spinny-circles 1k</a></p>      </div>
]]></description>
<pubDate>Thu, 12 Aug 2010 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>The quest for Extreme JavaScript Minification</title>
<link>http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/</link>
<guid>http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-293">
        <p><a href="http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/">The quest for Extreme JavaScript Minification</a></p>
<p>As <a href="http://blah.thingsinjars.com/post/292/elementally-my-dear-javascript/" title="Elementally, my dear JavaScript">described in detail previously</a>, I've recently taken part in the <a href="http://js1k.com">JS1K</a> competition where you have to squeeze something cool and clever into 1024 bytes of JavaScript. The quest to condense has become quite addictive and I found myself obsessing over every byte. This is the kind of stuff that the <a href="http://code.google.com/closure/compiler/">Closure Compiler</a> does quite well automatically but there are some cases where you just need to get in there and manually tweak.</p> 

<p>Here are some of the tricks I've picked up in my struggle for extreme minification:</p>

<h2>Basic improvements</h2>
<h3>Use short variable names.</h3> 
<p>This one's fairly obvious. A more useful addition to this is:</p>
<h3>Shorten long variable names.</h3>
<p>If you're going to be accessing an element more than once, especially if it's a built-in element like 'document', you'll save a few bytes every time you reference it if you create a shortened reference to it.</p>
<pre><code class="prettyprint">  document.body.style.overflow="hidden"
  document.body.style.background="red"
  (74 characters)
</code></pre>
<p>can shorten to</p>
<pre><code class="prettyprint">  d=document;b=d.body;s=b.style;
  s.overflow="hidden";
  s.background="red"
  (69 characters)
</code></pre>
<p>and any references to <code class="prettyprint">s</code> after are going to save 19 characters every time.</p>
<h3>Remove whitespace</h3>
<p>This one's so obvious, I don't need to mention it.</p>
<h3>Set Interval</h3>
<p>The extremely handy <code class="prettyprint">setInterval</code> function can take either a function or a string. If you give it an anonymous function declaration:</p>
<pre><code class="prettyprint">  setInterval(function(){x++;y--},10);
</code></pre>
<p>You will use up more characters than if you give it just the inside of the function as a string:</p>
<pre><code class="prettyprint">  setInterval('x++;y--',10);
</code></pre>
<p>But the outcome will be the same.</p>

<h2>Little-used aspects</h2>
<p>Not many people use JavScript's scientific notation unless they're doing scientific stuff but it can be a great byte saver. The number <code class="prettyprint">100</code> is equivalent to <code class="prettyprint">1 * 10^2</code> which is represented in JavaScript as 1E2. That's not a great saving for 100 but 1000 is 1E3, 10000 is 1E4. Every time you go up a factor of 10, you save 1 byte.</p>


<h2>Fight your good style tendencies</h2>
<p>In the war against space, you have to bite the bullet and accept that you may need to sacrifice some of your hard-earned practices. But only this once. Don't get in to the habit, okay?</p>
<h3>No zeroes</h3>
<pre><code class="prettyprint">  0.5  = .5
</code></pre>
<p>Yeah, it looks ugly but it works and saves a byte.</p>
<h3>Naked clauses</h3>
<pre><code class="prettyprint">  if {
    :
    :
  } else y
</code></pre>
<p>The <code class="prettyprint">y</code> looks so naked out there. No braces to keep it warm. But if you only have one statement in your else clause, you don't need them...</p>
<h3>No semi-final. . . final-semi. . . Semi-colon. No final colon.</h3>
<p>You don't need a semi-colon on your last line, even if it does make it look as though you've stunted its growth.</p>

<h2>The final few bytes</h2>
<h3>Operator precedence</h3>
<p>You don't need brackets. Brackets are handy for you as the programmer to remember what's going on when and to reduce ambiguity but if you plan correctly, most of the time you won't need brackets to get your arithmetic to work out.</p>
<pre><code class="prettyprint">  b.getMilliseconds()/(a*250) 
      is the same as
  b.getMilliseconds()/a/250 
</code></pre>
<h3>Shorthand notation</h3>
<pre><code class="prettyprint">  l=l+1;l=l%14;
  l++;l%=14;
  l=++l%14;
</code></pre>
<p>The three lines above are equivalent and in order of bytes saved.</p>
<h3>Shorthand CSS</h3>
<p>If you need to set some CSS values in your script, remember to pick the most appropriate short form. Instead of <code class="prettyprint">s.background='black'</code>, use  <code class="prettyprint">s.background='#000'</code> but instead of <code class="prettyprint">s.background='#F00'</code>, use <code class="prettyprint">s.background='red'</code>. In the same vein, the statements <code class="prettyprint">margin="0px"</code> and <code class="prettyprint">margin=0</code> mean the same but the latter saves bytes.</p>

<h2>Don't be generic</h2>
<p>One final thing to mention is that these little challenges are not the norm. If you find yourself trying to squeeze code down like this you're probably working on a very specific project. Use that to your advantage and see if there are any savings to be made by discarding your usual policies on code reuse. In the JS1K challenge, we're provided with a specific <a href="http://js1k.com/demo">HTML page</a> and an empty script tag. One good saving made here (and mentioned in my previous post) was the way I grabbed the reference to the canvas element. The standard method is to use the id assigned to the canvas.</p>
<pre><code class="prettyprint">  d.getElementById('c')
</code></pre>
<p>Which is a good generic solution. No matter what else was on the page, no matter what order stuff was in, this would return the canvas. However, we have a very specific case here and the canvas is always going to be in the same place - the first child of the body element. That means we can do this instead:</p>
<pre><code class="prettyprint">  b.children[0]
</code></pre>
<p>This makes use of the reference we grabbed to the body earlier. If the page were rearranged, this would stop working but as it won't, we've saved 8 bytes.</p>

<h2>In conclusion</h2>
<p>Yes, this is all quite silly but it's also fun and tricky. Attempting these kinds of challenges keep us developers mindful of what it is we actually do and that makes it an extremely productive silly hobby.</p>      </div>
]]></description>
<pubDate>Sun, 08 Aug 2010 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Elementally, my dear JavaScript</title>
<link>http://thingsinjars.com/post/292/elementally-my-dear-javascript/</link>
<guid>http://thingsinjars.com/post/292/elementally-my-dear-javascript/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-292">
        <p><a href="http://thingsinjars.com/post/292/elementally-my-dear-javascript/">Elementally, my dear JavaScript</a></p>
<p><a href="http://www.angryrobotzombie.com">The Angry Robot Zombie Factory</a> launched its second iPhone/iPad app this week. I haven't mentioned it much yet because I spotted a minor typo in the final version after it had been approved so I submitted an update immediately. To get an early copy (like those misprinted stamps where the plane is upside down), go check out <a href="http://itunes.apple.com/app/the-elementals/id383675775?mt=8">The Elementals</a>. It's free, too. It's a simple, cartoonish periodic table.</p>
<p>Yesterday, the <a href="http://js1k.com">1k JavaScript demo contest</a> (<a href="http://twitter.com/#search?q=js1k">#js1k</a>) caught my eye. The idea is to create something cool using 1024bytes of JavaScript or less. I rootled around in the middle of The Elementals, grabbed the drawing function and 20 minutes later had made <a href="http://js1k.qfox.nl/demo/21">my entry</a>.</p>
<p>The code I submitted is quite minified but isn't obfuscated. When it's unfolded, you can follow the flow fairly easily.</p>

<pre><code class="prettyprint">var d = document,
b = d.body,
s = b.style,
w = innerWidth,
h = innerHeight,
v = b.children[0],
p = 2 * Math.PI,
Z = 3,
x = tx = w / 2,
y = ty = h / 2;
</code></pre>

<p>The above is a bunch of declarations. Using things like <code class="prettyprint">d = document</code> and <code class="prettyprint">b = d.body</code> allows reuse later on without having to resort to the full <code class="prettyprint">document.body.style</code> and saves a bunch of characters. When you've got such a small amount of space to play with, every character counts (mind you, the <a href="http://en.wikipedia.org/wiki/ZX81">ZX81</a> only had 1k of RAM and look what you could do with that). Now that I'm looking at it, I think I could have tidied this a bit more. Darn. The sneaky bit about this code is the way we grab the reference to the canvas. The code <code class="prettyprint">d.getElementById('c')</code> uses 21 characters but if we look at the provided HTML, we can use the fact that the canvas is the first child of the body element. The code <code class="prettyprint">b.children[0]</code> uses 13 characters instead.</p>

<pre><code class="prettyprint">s.margin = "0px";
s.background = "black";
s.overflow = "hidden";
v.width = w;
v.height = h;
t = v.getContext("2d");
</code></pre>

<p>This sets the provided canvas to be the full width and height of the window then grabs the drawing context of it so we can make pretty pictures.</p>

<pre><code class="prettyprint">zi = function () {
 Z++;
 Z %= 14
};
m = function (X) {
 return (X * 200) % 255
};
</code></pre>

<p>Functions to be reused later. <code class="prettyprint">zi</code> increases the number of spinning circles and is used by onmousedown and ontouchstart (oh yes, it works on the iPad, too). <code class="prettyprint">m</code> is a mapping of the index of the circle to a colour. The 200 is arbitrary. I played about a bit until I found some colour combinations I liked.</p>

<pre><code class="prettyprint"> d.ontouchstart = function (e) {
 zi();
 tx = e.touches[0].pageX;
 ty = e.touches[0].pageY
};
d.onmousemove = function (e) {
 tx = e.clientX;
 ty = e.clientY
};
d.onmousedown = zi;
</code></pre>

<p>Setting the event handlers.</p>

<pre><code class="prettyprint">function r() {
 t.globalCompositeOperation = 'lighter';
</code></pre>

<p>I played about with the <a href="https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html">various composite operations</a>. Lighter seemed the nicest.</p>

<pre><code class="prettyprint"> t.clearRect(0, 0, w, h);
 t.save();
 x = x + (tx - x) / 20;
 y = y + (ty - y) / 20;
 t.translate(x, y);
</code></pre>

<p>Originally, the circles followed the mouse pointer exactly but it lacked any life. By adding in this bit where the movement is delayed as if pulling against friction, it suddenly became a lot more fun and dynamic.</p>

<pre><code class="prettyprint"> var c = new Date();
 for (var i = 1; i       </div>
]]></description>
<pubDate>Wed, 04 Aug 2010 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Crowdsourced Weather - Part 2</title>
<link>http://thingsinjars.com/post/255/crowdsourced-weather---part-2/</link>
<guid>http://thingsinjars.com/post/255/crowdsourced-weather---part-2/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-255">
        <p><a href="http://thingsinjars.com/post/255/crowdsourced-weather---part-2/">Crowdsourced Weather - Part 2</a></p>
<p>So, I couldn't help myself. I had a niggling idea at the back of my head that I needed to get out. After coming up with this <a href="http://blah.thingsinjars.com/post/254/crowdsourced-weather/">Twitter weather</a> idea last week, I decided to spend a couple of hours this weekend building it. As if I didn't have other things I should have been doing instead...</p>

<p>It works pretty much exactly how the pseudocode I mentioned last time describes. Every few minutes, a script will search Twitter for mentions of any weather words from several different languages. It will then look up the location of the person who tweeted that and store it. Single reports might be wrong and users might not have stored their actual location but over a large enough sample, this system becomes more accurate. The script removes any matching twets older than 6 hours.</p>

<p>To display, I actually ended up using <a href="http://en.wikipedia.org/wiki/Geohash">Geohashes</a> instead of <a href="http://www.geotude.com/">Geotudes</a> because it is easier to simplify them when you zoom out just by cutting off the tail of the hash. For example, the physical area denoted by gcvwr3qvmh8vn (the geohash for Edinburgh) is contained within gcvwr3 which is itself contained within gcv. There are a few <a href="http://en.wikipedia.org/wiki/Geohash#Limitations">technical problems with geohashes</a> but it seems the best fit for this purpose. If anyone knows of any better suggestion, please let  me know. I do realise that this is quite possibly the slowest, most inefficient JavaScript I've ever written because it makes an AJAX call for every <a href="http://wiki.xkcd.com/geohashing/Graticule">graticule</a> and it probably should just send the South-East and North-West bounds and get back an array of them but, like I said, there were other things I should have been doing. Because the overlaid grid changes resolution based on zoom level, there are a few places where it is either tragically slow (resolution too fine) or terribly inaccurate (resolution too rough). That's just a case of tweaking the algorithm. Similarly, it's set to display reports of weather if there are 2 or more matches but it could be tweaked to only show if a larger number have reported something.</p>

<p>So go, play with the <a href="http://blah.thingsinjars.com/widgets/weather/index.html">Twitter-generated weather map</a>. If someone can come up with a good, catchy name, or some better graphics, that'd be great, thanks.</p>


<p>Source code is available: <a href="http://thingsinjars.com/uploaded/other/twitter-weather-1.0.zip">twitter-weather-1.0.zip [Zip - 298KB]</a>.</p>
<p>You'll need your own Twitter login and database account to use it.</p>
      </div>
]]></description>
<pubDate>Mon, 21 Dec 2009 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Crowdsourced Weather</title>
<link>http://thingsinjars.com/post/254/crowdsourced-weather/</link>
<guid>http://thingsinjars.com/post/254/crowdsourced-weather/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-254">
        <p><a href="http://thingsinjars.com/post/254/crowdsourced-weather/">Crowdsourced Weather</a></p>
<p>This is a more general version of the <a href="http://uksnow.benmarsh.co.uk/">#uksnow map</a> idea. It's a crowd-sourced weather map which relies on the fact that any one individual tweet about the weather might be inaccurate but given a large enough sample, enough people will mention the weather in their area to make this a workable idea. It doesn't require people to tweet in a particular format.</p>

<h2>To get info</h2>

<pre>
Have an array of weather words in various languages (rain, hail, snow, schnee, ame, yuki)
every 5 minutes:
	foreach weatherword
		search twitter for that word
			http://search.twitter.com/search.atom?q=rain
		retrieve latest 100 tweets
		foreach
			get user info
				http://twitter.com/users/show.xml?screen_name=username
			get user.location if available
			geocode
			save:
				username, time, lat, long, <a href="http://www.geotude.com/">geotude</a>, weatherword
		Remove any tweets about this weatherword older than 6 hours.
			
</pre>

<h2>To display info</h2>
<pre>
Show a Google map
Based on current Zoom level, split the current map into about 100 geotudes
foreach geotude
	search database for any weather results for that block (probably using an ilike "1234%" on the geotude field)
	sort by weatherword count descending
	draw an icon on top of that block to show the most common weatherword
	
If the user zooms in, recalculate geotudes and repeat.
</pre>

<p>I quite like that this uses <a href="http://www.geotude.com/">geotudes</a> which I think are an excellent idea.</p>

<p>I built a <a href="http://blah.thingsinjars.com/widgets/weather/">very basic version of this</a>. Read more about it in <a href="http://blah.thingsinjars.com/post/255/crowdsourced-weather---part-2/">Part 2</a>.</p>
      </div>
]]></description>
<pubDate>Thu, 17 Dec 2009 00:00:00 GMT</pubDate>
<category>js css</category>
</item><item>
<title>Some simple tips</title>
<link>http://thingsinjars.com/post/251/some-simple-tips/</link>
<guid>http://thingsinjars.com/post/251/some-simple-tips/</guid>
<description><![CDATA[
        <div class="teaser html" id="teaser-251">
        <p><a href="http://thingsinjars.com/post/251/some-simple-tips/">Some simple tips</a></p>
<p><em>The views and opinions expressed within are not those of National Museums Scotland. This site is in no way affiliated with National Museums Scotland or the website <a href="http://www.nms.ac.uk/">www.nms.ac.uk</a></em></p>
<p>First of all, the disclaimer: I am not a designer. If I were to make claim to being anything creative it's an <a href="http://permanentpencil.com">illustrator</a> but there's a huge difference between the two (I've always said that an illustrator makes the thing to go on the t-shirt, the designer says <em>where</em> on the t-shirt it goes). Despite the recent trend for everyone to call themselves web designers, I'm still going to go by web developer. I make things.</p>
<p>Bearing that in mind, there are still quite a few web design and UX tips and techniques I've picked up along the way which can be applied to most sites and not interfere with the mysterious ways of designers.</p>
<p>Recently, I've been reworking templates for <a href="http://www.nms.ac.uk/">National Museums Scotland</a> for faster load times and better SEO and I'll illustrate what I'm talking about with a couple of examples from there. The brief on these templates is that the content can't really change and there are some chunks that the CMS generates which can't be changed. Note: the NMS templates are completely finished yet and those that are haven't been rolled out across the whole site but sticking with that whole <a href="http://en.wikipedia.org/wiki/Release_early,_release_often">release early, release often</a> way of doing things, these little incremental improvements can be applied without affecting too much else.</p>

<p>For reference, here are before and after screen grabs of two of the templates.</p>
<ul class="gallery">
<li><a href="http://thingsinjars.com/uploaded/images/tips-our-before.jpg" rel="lightbox[1]" title="Main Gateway before"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-our-before.jpg" alt="Our Museums Before"/></a></li>
<li><a href="http://thingsinjars.com/uploaded/images/tips-our-after.jpg" rel="lightbox[1]" title="Main Gateway after"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-our-after.jpg" alt="Our Museums After"/></a></li>
<li><a href="http://thingsinjars.com/uploaded/images/tips-war-before.jpg" rel="lightbox[1]" title="Museum page before"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-war-before.jpg" alt="Museum gateway before"/></a></li>
<li><a href="http://thingsinjars.com/uploaded/images/tips-war-after.jpg" rel="lightbox[1]" title="Museum page after"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-war-after.jpg" alt="Museum gateway after"/></a></li>
</ul>

<p>Some people will find these tips blatantly obvious but the fact that pages still get made without considering these means they do need reiterating.</p>

<h2>Link the Logo</h2>
<p>The web's been around for a few years now and there are a few conventions users have gotten used to. One of them is that the logo is a link that takes you back to the home page. It doesn't harm anything to have a link there so even if 99% of visitors don't use it, why annoy the 1% who do?</p>

<h2>Don't link to the search</h2>
<p>From the moment the visitor decides they want to search your site for something, the most important thing is to get the results in front of them as quickly as possible. It therefore makes for a better experience if you bring the results one step closer to them. Rather than requiring the user to click on a link to get to the search form to do their search to get the results, put the search box on every page. They fill it in and go to the results page. If the user wants to take advantage of any advanced search features you may have, they can modify their search from the results page.</p>
<p><img src="http://thingsinjars.com/uploaded/images/tips-search.jpg" alt="Search box positioned within header"/></p>

  <p>Note: the new template still contains a link to the search page due to some legacy requirements. I don't actually recommend this.</p>


<h2>Line up</h2>
<ul class="gallery">
  <li><a href="http://thingsinjars.com/uploaded/images/tips-line-a.gif" rel="lightbox[2]" title="Higglty.."><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-line-a.gif" alt="thumbnail of layout not aligned"/></a></li>
  <li><a href="http://thingsinjars.com/uploaded/images/tips-line-b.gif" rel="lightbox[2]" title="...and straight"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-line-b.gif" alt="thumbnail of layout aligned"/></a></li>
</ul>
<p>I'm sure there's more to design than this but there are a couple of well tested rules I recommend any non-designer to learn:</p>

<ol>
       <li>If it doesn't line up, make it line up.</li>
       <li>If it's already lined up, make it not.</li>
</ol>

<p>That and a subscription to iStock and you're done...</p>

  <p>Note: This was a joke, real designers please don't stab me with your crayons.</p>


<h2>Make the hit area as big as possible</h2>
<ul class="gallery">
  <li><a href="http://thingsinjars.com/uploaded/images/tips-hit-a.jpg" rel="lightbox[3]" title="Before and after close-up"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-hit-a.jpg" alt="Thumbnail of gateway panel comparison" /></a></li>
  <li><a href="http://thingsinjars.com/uploaded/images/tips-hit-b.jpg" rel="lightbox[3]" title="Blue bits are clickable"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-hit-b.jpg" alt="Thumbnail of gateway panel hit area comparison" /></a></li>
</ul>
<p>From the gateway page for <a href="http://www.nms.ac.uk/our_museums.aspx">Our Museums</a>, there are two ways the user could go. They were either looking for opening times (in which case, they're done), or they want to find out more information about the individual museums on their own pages. To that end, it makes sense to make the next step as easy as possible and bascially turn the content this page into six huge buttons. To keep everything semantic, JavaScript has been used here to extract the destinations from each of the links and apply them to the whole panel area (it'll default to linked text and image with JavaScript disabled). As you can see, doing this changes the hit area for each museum from a line of text to a veritable barn door.</p>

<h2>White text on a white background is not good</h2>
<ul class="gallery">
  <li><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-white-a.jpg" alt="white text laid over white background"/></li>
  <li><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-white-b.jpg" alt="white text laid over black background"/></li>
</ul>
<p>Actually, I'm not sure whether it's the fact that the link wasn't as readable as it could have been or the fact that to go home requires poking her in the eye that upset me most. Either way, if you do need to use an image that has a light bit underneath some light text and you can't shuffle it along like here, a quick wipe with the burn tool in Photoshop works wonders.</p>

<h2>Underline links</h2>
<p>I'm not going to get into the debate over whether or not <a href="http://www.gerrymcgovern.com/nt/2009/nt-2009-11-02-Web-links-actio n.htm">designers hate underlines</a> but for a high-traffic, public sector with an extremely varied demographic, I'd recommend using them. As <a href="http://boagworld.com/podcast/191">Paul Boag</a> mentions, what you do with your design and your solutions for various usability issues depends on the audience. A graphic designer's portfolio might very well eschew underlines when denoting links, a government site probably shouldn't. Especially when you remember that you should <a href="http://www.webaim.org/standards/508/checklist">never rely on colour alone to convey information</a>, including whether not a piece of text is a link.</p>

<h2>Titles are titles of something</h2>
<ul class="gallery">
  <li><img src="http://thingsinjars.com/uploaded/images/tips-related-a.gif" alt="titles far away from paragraph text"/></li>
  <li><img src="http://thingsinjars.com/uploaded/images/tips-related-b.gif" alt="titles near paragraph text"/></li>
</ul>
<p>If you have a title, it generally refers to the thing below it, not the thing above it. Make sure you keep titles and the things they are titles of together.</p>

<h2>Avoid disparate navigation</h2>
<ul class="gallery">
  <li><a href="http://thingsinjars.com/uploaded/images/tips-nav-a.gif" rel="lightbox[4]" title="Several different navigations"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-nav-a.gif" alt="navigation split over two areas"/></a></li>
  <li><a href="http://thingsinjars.com/uploaded/images/tips-nav-b.gif" rel="lightbox[4]" title="Slightly combined"><img src="http://thingsinjars.com/uploaded/images/thumbs/tips-nav-b.gif" alt="navigation combined into one area"/></a></li>
</ul>
<p>Again, another of the rules of web that has evolved over the last several years: Sections go along the top, navigation down the side. To keep consistent with the rest of the site the horizontal museum links were brought down and integrated with the rest of the navigation. This maybe isn't the most illustrative example but, basically, don't have a top nav, left nav, right nav and several others when you could have just one.</p>

<h2>Only a fraction</h2>
<p>There we are, a few handy little tips for your next build project. This hasn't gone into any issues of column width, line-height - or <a href="http://en.wikipedia.org/wiki/Leading">leading</a> (pronounced /ˈlɛdɪŋ/) as designers call it, hover states or any of the myriad other things it could, just a few of the more important and easy-to-do ones.</p>      </div>
]]></description>
<pubDate>Mon, 07 Dec 2009 00:00:00 GMT</pubDate>
<category>js css</category>
</item></channel>
</rss>