Tuesday, September 28, 2010

jQuery plugin to disable text selection on elements

It took my a while to find a bit of script that worked cross browser, but the jquery plugin at http://code.jdempster.com/jQuery.DisableTextSelect/ does the job!
When working on the UI of a web application text would often get selected by the browser incorrectly, for example while dragging an element, or clicking on an element with an onclick event.
If you are using jquery already; download it, include it, then use:
$(‘.elementsToDisableSelectFor’).disableTextSelect();
If you need this functionality without including the whole of jquery, take a look at the source code for the plugin. It’s only about 20 lines long. It uses a different method for Firefox and Internet Explorer, with a fallback for everything else but it should be easy to convert in to native JS or another javascript framework.

(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : ''
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart.disableTextSelect', function() {
                    return false;
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).unbind('selectstart.disableTextSelect');
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('mousedown.disableTextSelect', function() {
                    return false;
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).unbind('mousedown.disableTextSelect');
            });
        };
    }
})(jQuery);

http://www.blograndom.com/blog/2009/07/jquery-plugin-to-disable-text-selection-on-elements/

HTML5 Local Storage – Complete Guide

HTML5 is one of the most fashionable topics in today’s web programming world. HTML5 contains lots of new features that allege to change the web face, big players like Google and Apple are pushing for it and browsers competes to implement more and more html5 features. In this conditions there is no surprise that everyone is talking about it.
In this post we are going to analyse exhaustively an HTML5 simple feature which is already implemented in all the modern browsers: local storage. Local Storage is just a part of the Web Storage api. It is already defined in the HTML5 specifications and it’s implemented in all the modern browsers:

IE Firefox Safari Chrome Opera IPhone Android
8+ 3.5 4.0+ 4.0+ 10.5+ 2.0+ 2.0+

Local Storage is intended to be used for storing and retrieving data in html pages from the same domain. The data can be retrieved from all the windows in the same domain even if the browser is restarted. The Session Storage is the other Web Storage option and the data is available only in the window it was stored in and is lost when the browser window is closed.
Local Storage along with Session Storage aims to be a replacement of the cookies, defining a more consistent API. There are a few differences from the cookies:
- While the cookies are accessible from both client and server side, Web Storage in general and Local Storage in particular is accessible only from client side.
- Enhanced capacity(official for cookies is 4 kbytes) to more than 5Mb per domain(Firefox, Google Chrome, and Opera and 10MB in IE).
The local storage is a simple javascript api that you can use inside html5 pages if it’s supported by the browser. The Local Storage implements the same interface that can be used for Session Storage as well. Here is the interface as it is defined by :
  1. interface Storage {  
  2.   readonly attribute unsigned long length;  
  3.   getter DOMString key(in unsigned long index);  
  4.   getter any getItem(in DOMString key);  
  5.   setter creator void setItem(in DOMString key, in any value);  
  6.   deleter void removeItem(in DOMString key);  
  7.   void clear();  
  8. };  

Testing if the browser supports Local Storage

When you intend to use Local Storage you have to take in consideration that it is not supported by all the browsers. If the correct run of your application depends on the local storage functionality you have find other features to rely if it’s not supported, or to inform the user that the application doesn’t run properly on his browser. In order to check if it’s supported you have to check if the localStorage instance exists.
  1. function testSupport()  
  2. {  
  3.     if (localStorage)  
  4.         return "Local Storage: Supported";  
  5.     else  
  6.         return "Local Storage: Unsupported";  
  7. }  

How to Store a Value

Storing values is very simple, all you have to do is to invoke the setItem method, providing a key and a value, or to use use the localStorage object as an associative array:
  1. localStorage.setItem("key1""value1");  
  2. localStorage["key1"] = "value1";  

How to Retrieve a Value

Retrieving stored values is as simple as possible:
  1. alert(localStorage.getItem("key1"));  
  2. alert(localStorage["key1"]);  

List all stored values

If you need to check all the values stored in local storage you can iterate through the keys, listing the values accordingly.
  1. function listAllItems(){  
  2.     for (i=0; i<=localStorage.length-1; i++)  
  3.     {  
  4.         key = localStorage.key(i);  
  5.         val = localStorage.getItem(key);  
  6.     }  
  7. }  

Remove a Value

Compared to cookies, html5 local storage has a much bigger capacity. However, it doesn't mean it's unlimited. If you application uses intensively the local storage, you have to take care to remove the objects you don't need anymore.
  1. void removeItem("key1");  

Clear all the values

When the web application is "closed" or "started" you can clean all the stored values:
  1. localStorage.clear(); 

An (Almost) Complete Guide to CSS3 Multi-column Layouts

One of the defining features of print design is the ubiquity of multi-column layouts. And there are a couple of good reasons why this is the case.
First of all, it’s generally easier to read lines of text between 8 and 12 words long. Second, it’s easier to control the amount of negative space in a layout with columns. For a long time, this was the primary advantage of print but CSS3 makes multi-column layouts possible online (and without the need for JavaScript).
W3C Specification: http://www.w3.org/TR/css3-multicol/

Browser Specific Support

WebKit support: Strong
Firefox support: Strong
IE9 support: None

The multi-column model

The WC3 specification introduces a number of new properties that allow us to define columns in HTML layouts. Just like print designs of old, we’re able to define the number of columns, column width, column gaps, and even rules governing overflow.
Essentially, the specification states that a multi-column element needs to have either a defined column width or column count. Browsers are supposed to render these elements similar to the way they render tables – but the content in a column layout is dynamically split into blocks.
At the moment, we’re not able to define certain properties about columns (like column-specific backgrounds), but it’s possible this might change.

The number and width of columns

column-count and column-width are the two most basic ways to define the properties of a multi-column element.

column-count

By default, column-count is set to auto. This means that if we explicitly define the column-width, the browser will sort out for itself how many columns are necessary to populate the content in the multi-column element. Obviously, that’s not always desirable so we’ll want to explicitly define the number of columns to span the content across. And it’s easy to do:
1#multicolumnElement {
2    -webkit-column-count: 2;
3    -moz-column-count: 2;
4    column-count: 2;
5}

column-width

As I mentioned, we can define column-width without defining the number of columns, and the browser will render our content dynamically (there are some fine controls available too – keep reading for those). To define column-width, we can use any of the units regularly available to CSS properties (em, px, %, etc).
1#multicolumnElement {
2    -webkit-column-width: 15em;
3    -moz-column-count: 15em;
4    column-count: 15em;
5}
Of course, we can always combine column-width and column-count:
1#multicolumnElement {
2    -webkit-column-count: 2;
3    -moz-column-count: 2;
4    column-count: 2;
5    -webkit-column-width: 15em;
6    -moz-column-width: 15em;
7    column-width: 15em;
8}

Column gaps and rules


All print designers are familiar with column widths and gaps, but web designers are addicted to the language of margins and padding.
But column gap is exactly as it sounds – the size of the space between columns defined in any unit regularly available in CSS (em, pixel, etc).

column-gap

The WC3 specification defines 1em as the default column-gap value, so we’ll use it in this example:
1#multicolumnElement {
2    -webkit-column-gap: 1em;
3    -moz-column-gap: 1em;
4    column-gap: 1em;
5}

column-rule

Column rule is another throwback to the print era. Basically, column rules are thin lines between the columns, to further aid readibility and/or to distinguish between separate stories. CSS3 gives us three different properties for the column rule: column-rule-size, column-rule-style, and column-rule-color, but we can use the shorthand column-rule to declare values for all three at once.
As you might have guessed, the regularly available units, styles, and color values can all be used:
1#multicolumnElement {
2    -webkit-column-rule: 1em solid #000;
3    -moz-column-rule: 1em solid #000;
4    column-rule: 1em solid #000;
5}

Column breaks

What if I want to break the column before an h3 tag, you ask? Well, that’s easy too. CSS3 gives us the column-break property with a number of possible related properties and values, including: auto, always, avoid, left, right, page, column, avoid-page, and avoid-column.

column-break

So if we want to break the content before every h3 tag we simply include the column-break-before property in our stylesheet:
1h2 {
2    -webkit-column-break-before:always;
3    -moz-column-break-before:always;
4    column-break-before:always;
5}

Spanning columns

If we want an element, say a headline, to span across multiple columns we can make use of the new column-span property.

column-span

column-span has two possible values: all, and regular numbers (e.g. 1,2,3). Defining column-span as all means that the given element will span across the whole multi-column block, while assigning it a regular number will limit its span to that number of columns:
01h2 {
02    -webkit-column-span:all;
03    -moz-column-span:all;
04    column-span:all;
05}
06
07h3{
08    -webkit-column-span:2;
09    -moz-column-span:2;
10    column-span:2;
11}

Filling columns

Just like print design, we might want some finer control over how columns are filled with content. CSS3 introduces column-fill to give us that kind of control.

column-fill

We can either define a value of auto or balanced. The former will sequentially fill columns with content, while the latter evenly distributes the content.
1#multicolumnElement {
2    -webkit-column-fill:auto;
3    -moz-column-fill:auto;
4    column-fill:auto;
5}

Demo!


To cap things off, I’ve created a quick demo project based on the first few paragraphs of Moby Dick. It should display correctly in both WebKit and Mozilla based browsers (though it’s not formatted properly for mobile).

http://www.kmsm.ca/2010/an-almost-complete-guide-to-css3-multi-column-layouts/

Sunday, September 19, 2010

imgAreaSelect

imgAreaSelect is a jQuery plugin for selecting a rectangular area of an image. It allows web developers to easily implement image cropping functionality, as well as other user interface features, such as photo notes (like those on Flickr).
Plugin features:
  • Highly configurable
  • Customizable with CSS styling
  • Handles scaled images
  • Keyboard support for moving and resizing the selection
  • Supports callback functions
  • Provides API functions for easier integration with other application components
  • Lightweight — the packed version is less than 8KB
The plugin works in all major browsers, including Firefox 2+, Opera 9.5+, Google Chrome, Safari 3+, and Internet Explorer 6+.

http://odyniec.net/projects/imgareaselect/

Extending media queries with JavaScript

Media queries are cool: you can decide what CSS file to serve to a browser based its width. But although it works perfect in many modern browsers, there are always some browsers or some versions of it lagging. Let’s give them a hand.

What are media queries

To explain what media queries are, it’s best to start with the standard media types. Media types were introduced as part of the CSS2 specification way back in 1998 and is supported by all major browsers. The most common are “screen” (desktop PC’s), “handheld” (mobile devices), and “print”.
This looks pretty straightforward and it is. But most mobile browsers don’t consider themselves “handheld” when choosing a CSS file. Devices like iPhone, Android and Nokia behave like a desktop computer and select the CSS that’s reserved for the “screen”-devices.
This was in some way a logical step, since most websites don’t have a CSS file for handheld devices. The drawback is also very clear: You cannot cram a web page optimized for desktop monitors in a 2′ handheld monitor without paying a price. Usability suffers. Users are given crutches like the ability to zoom in to a specific part of the page, but that’s like watching TV through a keyhole.
To address this problem the W3C came with media queries.
Now we have all our ducks back in a row. If the browser width is larger than 480 pixels, it will select “screen.css”. If the width is smaller or equal to 480 pixels, it will go for “handheld.css”. We keep our CSS link with media="handheld" as a fallback for handheld devices that don’t do media queries, most notably IE Mobile and Blackberry’s browser. Checkout PPK’s compatibility table to see which browser does not support Media Queries yet.

Filling the gaps

But this still is not enough to have your site render well in all browsers. IE and many older browsers do not handle the new media queries.
Some sort of solution was proposed on ALA, but that technique requires an extra CSS file called antiscreen.css that cancels some of all styles that were created in the screen.css. Most of the websites I make just have too much CSS styling to make that technique usable.
JavaScript can also detect the screen width, so I decided to use it to help browsers in choosing the right CSS. The script I created also checks the screen width after a window resize, just like Media Queries. Just open the demo and you will see that the page will switch to the mobile stylesheet if the window gets too narrow. Even in browsers that don’t support Media Queries (yes, I’m looking at you, IE!).

How it works

In the demo the script expects that if Media Queries are supported by the browser, a div with the class cssLoadCheck should be 100 pixels in width. To check that it this is true it will insert a div with that class into the DOM, check its width and then removes it from the DOM again. If the width of that test div isn’t 100 pixels we know that Media Queries are not supported and that JavaScript has to supply a CSS file depending on its width.
Each time the pages refreshes it removes the dynamically added link-tags in the head and adds new ones.

http://www.thebrightlines.com/2010/09/11/helping-browsers-with-media-queries/

Saturday, September 11, 2010

Rails 3 Doesn't Autoload Modules In Lib

Rails 3 doesn’t autoload modules/code in lib by default. To fix it add the following code to your config/application.rb.
config.autoload_paths += %W(#{config.root}/lib)

Tuesday, September 7, 2010

The HTML5 test – how well does your browser support HTML5?

  1. Parsing rules
  2. Canvas
  3. Video
  4. Audio
  5. Local devices
  6. Elements
  7. Forms
  8. User interaction
  9. Microdata
  10. Web applications
  11. Geolocation
  12. Communication
  13. Files
  14. Storage
  15. Workers
http://www.html5test.com/

    Smoothie Charts


    Smoothie Charts is a really small charting library designed for live streaming data. I built it to reduce the headaches I was getting from watching charts jerkily updating every second. What you're looking up now is pretty much all it does. If you like that, then read on.
    It currently only works in Chrome and Safari 5.
     http://joewalnes.com/2010/08/10/introducing-smoothie-charts/

    Monday, September 6, 2010

    Jasmine – A JavaScript Testing Framework

    There are some great JavaScript testing frameworks out there. Many only work from within a browser. Most don’t support testing asynchronous code like event callbacks. Some have syntax that’s hard for JS developers or IDEs to understand.
    Jasmine is a JavaScript testing framework. It’s heavily influenced by, and borrows the best parts of, ScrewUnit, JSSpec, JSpec, and of course RSpec. Jasmine is not tied to any browser, framework, platform, or host language. It work anywhere JavaScript can run, including browsers, servers, phones, etc.
    testing-framework


    http://pivotal.github.com/jasmine/
    http://www.webappers.com/2010/09/02/jasmine-a-javascript-testing-framework/

    Visualising sorting algorithms

    This is another one of my rare technical posts, as opposed to news of which countries I've been visiting.

    If you're in computer science, you've probably seen an animation of sorting algorithms, maybe heard a rendition, or seen a visual representation. I have, somewhat by accident, discovered a different way to visualise a sorting algorithm: plot points for memory accesses, with address on the X axis and time (counted by accesses) on the Y axis, and different colours for reads and writes. It produces some rather pretty pictures. Note that these are not to scale relative to each other - the Y axis has been compressed to fit the entire sort into a fixed height.

    Ye olde bubblesort. Some of the patterns are an optical illusion due to aliasing, but the green spikes are a feature of the algorithm.

    Insertion sort - the version optimized for mostly sorted content. Although the data is random, you can see that in many cases it reduces the search distance.Shellsort, clearly showing the phases.

    Selection sort:Heapsort: the solid lines at the top are the heap-building phase, while the rest shows the extraction. Note the very slight slope to the bottom-right line: as the heap gets smaller, the heap extraction gets faster, but only as O(log N).
    Divide-and-conquer algorithms have a pretty fractal nature. This is quicksort - the perturbations in the fractal indicate the random selection of pivots (it just picks the middle, rather than median-of-3). Mergesort: this diagram is twice as wide as the others because it uses temporary storage on the right.


    http://blog.brucemerry.org.za/2010/09/visualising-sorting-algorithms.html