Mustache.js et ICanHaz.js au secours de jQuery

=>SOURCE<=

1. jQuery sans les moustaches

Imaginons qu’on veuille afficher une liste de livres (titre, auteur) que l’on récupère sous forme d’objets Javascript. Voici le code Javascript/jQuery correspondant :

var book = { title: "Javascript: the Good Parts", author: "Douglas Crockford" };
$('#example').append('Title: <b>' + book.title + '</b><br/>Author: ' + book.author);

Et le résultat :

Title: Javascript: the Good Parts
Author: Douglas Crockford

Je ne sais pas vous mais cette ligne là, elle m’irrite un peu quand je la lis et encore plus quand je l’écris :

$('#example').append('Title: <b>' + book.title + '</b><br/>Author: ' + book.author);

Pleins de ' et de +, c’est facile de s’y perdre et surtout on mélange affichage et données. En Java, il existe de nombreux systèmes de templates pour mettre en oeuvre cette séparation : VelocityFreemarkerStringTemplate et j’en passe. Et bien en Javascript, il existe également des systèmes de template dont Mustache, que je trouve simple et pourtant très puissant. Alors faisons appel à Mustache.js et voyons comment on peut rendre l’exemple précédent plus sexy.

var data = {title: "Javascript: the Good Parts", author: "Douglas Crockford"};
var template = 'Title: <b>{{title}}</b> <br/> Author: {{author}}';
var output = Mustache.render(template, data);
$('#example').append(output);

Title: Javascript: the Good Parts
Author: Douglas Crockford

Aaah fini les ' et + parasites ! On a maintenant une belle séparation entre le template et les données. On utilise Mustache.render qui prend en paramètre le template et notre objet de données data. Dans le template, il y a deux tags {{title}} et {{author}} qui vont être remplacés par les valeurs correspondantes de l’objet data lors de l’appel àMustache.render.

On peut faire donc une première observation, un template Mustache est composé de tags et un tag est délimité par des doubles accolades : les fameuses moustaches !

2. Les tags Mustache

Pour l’instant, nous n’avons vu qu’un type de tag {{name}} qui permet d’afficher la valeur de l’attribut name de votre objet de données. Dans le jargon Mustache, name est la clé du tag. Voici un petit listing des tags Mustache qui existent :

{{#name}}, la moustache de section

Ce tag va ouvrir ce que Mustache appelle une section. Cette section peut contenir du text/html ou des tags Mustache. Une section est fermée par un tag {{/name}}. Si l’attribut name existe dans votre objet de données et est non null, non vide, non undefined alors Mustache va interpréter cette section. Dans le cas contraire, la section n’est pas interprétée.

var data = {title: "Javascript: the Good Parts", author: ""};
var template = '{{#title}} Title: <b>{{title}}</b> {{/title}} {{#author}} ne sera pas affiché {{/author}}';
var output = Mustache.render(template, data);
$('#example').append(output);

Title: Javascript: the Good Parts

Si name est un array, alors Mustache va itérer sur cet array et interpréter la section autant de fois que nécessaire.

var data = { books: [ "Javascript: the Good Parts", "Clean Code" ] };
var template = '{{#books}}<li>{{.}}</li>{{/books}}';
var output = Mustache.render(template, data);
$('#example').append(output);
  • Javascript: the Good Parts
  • Clean Code

Notez l’utilisation de {{.}} afin d’afficher l’élément de l’array.

{{^name}}, la moustache inverse

C’est l’inverse du tag {{#name}}, c’est-à-dire que le body du tag ne sera interprété que si l’attribut name n’existe pas, est vide, null ou undefined dans votre objet de données. Exemple :

var data = { books: [ ] };
var template = '{{#books}}<li>{{.}}</li>{{/books}} {{^books}}Aucun livre{{/books}}';
var output = Mustache.render(template, data);
$('#example').append(output);

Aucun livre

{{! comment}}, la moustache invisible

C’est le tag de commentaire. Tout ce qu’il y a entre les moustaches est ignorée.

var data = {title: "Javascript: the Good Parts", author: "Douglas Crockford"};
var template = 'Le commentaire suivant ne sera pas affiché : {{! ne doit pas être affiché}}';
var output = Mustache.render(template, data);
$('#example').append(output);

Le commentaire suivant ne sera pas affiché :

{{> tag}}, la moustache partielle

Avec Mustache, il est possible de définir des templates partiels afin de décomposer des templates qui seraient trop verbeux ou des templates que vous récupérez de plusieurs sources.

var data = {title: "Javascript: the Good Parts", author: "Douglas Crockford"};
var template = 'Title: <b>{{title}}</b> <br/>{{> tplAuthor}}';
var partials = { tplAuthor: 'Author: {{author}}' };
var output = Mustache.render(template, data, partials);
$('#example').append(output);

Title: Javascript: the Good Parts
Author: Douglas Crockford

3. Fonctions

Dans votre objet de données, vous n’êtes pas cantonnés à avoir uniquement des valeurs ou des arrays. Vous pouvez également définir des fonctions qui vont déterminer le texte à afficher. Exemple :

var i = 0;
var data = { currentdate: function() { return i++;} };
var template = '<li>{{currentdate}}</li>';
$('#example').append(Mustache.render(template, data));
$('#example').append(Mustache.render(template, data));
$('#example').append(Mustache.render(template, data));
  • 0
  • 1
  • 2

Ok j’avoue, ça c’était l’exemple facile avec les fonctions. On peut faire un poil plus évolué. Dans les exemples précédents avec les livres, on affiche le titre en gras. Imaginons qu’on veuille rendre paramétrable l’affichage de “Title”, donc au choix en gras, en italique ou ce que vous voulez. Il suffit de fournir une fonction qui va faire ça.

var data = {
  title: "Javascript: the Good Parts",
  titleDisplay: function() {
    return function(text, render) {
      return '<b>' + render(text) + '</b>';
    }
  }
};
var template = 'Title: {{#titleDisplay}} {{title}} {{/titleDisplay}}';
var output = Mustache.render(template, data);
$('#example').append(output);

Title: Javascript: the Good Parts

Mais maintenant si je veux afficher le titre en italique et l’entourer par des guillemets, on remplace le corps de la fonction par :

return '"<i>' + render(text) + '</i>"';

Title: “Javascript: the Good Parts

Donc celui qui fournit l’objet data peut maintenant personnaliser l’affichage du titre.

4. Template multi lignes

“T’es bien gentil Ludo, mais tes exemples sont simplistes, tes templates ne tiennent que sur une seule ligne. Tiens prend ce template là. C’est beaucoup moins beau du coup et on peut vite oublier un antislash…”

var template = 'Title: {{title}} <br/>\
Author: {{author}} <br/>\
Edition: {{edition}}';

Effectivement, ce n’est pas très sexy. Alors il y a une petite astuce. Il suffit de mettre le template dans une balise <script> de type text/html, de récupérer son contenu et de le passer à Mustache ! En exemple ça donne :

<script id="book" type="text/html">
Title: {{title}} <br/>
Author: {{author}} <br/>
Edition: {{edition}}
</script>

 

var data = {title: "Javascript: the Good Parts", author: "Douglas Crockford", edition: "O'Reilly"};
var template = $('#book').html();
var output = Mustache.render(template, data);
$('#example').append(output);

Title: Javascript: the Good Parts
Author: Douglas Crockford
Edition: O’Reilly

Mais on peut faire encore mieux !

5. ICanHaz.js

ICanHaz.js est une petite librairie Javascript qui wrappe Mustache.js et qui reprend l’idée de définir ses templates dans des balises script de type text/html. Au chargement de la page, ICanHaz.js va rechercher tous les templates de la page, créer un cache contenant ces templates et une fonction pour chaque template. A l’utilisation, c’est encore plus simple que Mustache.js. Si on reprend l’exemple précédent, le javascript devient :

<script id="book" type="text/html">
Title: {{title}} <br/>
Author: {{author}} <br/>
Edition: {{edition}}
</script>

 

var data = {title: "Javascript: the Good Parts", author: "Douglas Crockford", edition: "O'Reilly"};
var output = ich.book(data);
$('#example').append(output);

ICanHaz.js fournit un objet ich et a créé une méthode book correspondant à l’id de la balise script. ICanHaz.js permet également de gérer les partials Mustache de manière élégante en indiquant un attribut à la balise script. Si on remplace la partie “edition” par un partial :

<script id="book" type="text/html">
Title: {{title}} <br/>
Author: {{author}} <br/>
{{> edition}}
</script>
<script id="edition" type="text/javascript">
Edition: {{edition}}
</script>

et l’appel à ich.book(data) reste le même !

Comme je vous le disais précédemment, ICanHaz.js gère un cache de templates et fournit donc des méthodes pour rajouter des templates dans le cache, nettoyer le cache ou recharger le cache.

Conclusion

Si, sur votre projet, vous utilisez jQuery et n’utilisez pas de système de template côté client, alors foncez ! Essayez Mustache.js et ICanHaz.js ! Le tout ne fait que 5,4ko minifié.
Ensuite, je voudrais donner quelques précisions sur Mustache.js. Mustache.js est en fait l’implémentation Javascript du système de template Mustache (sans le .js). En effet, il existe de nombreuses implémentations de Mustache, en Java, Ruby, Python, PHP, etc…
De plus, on dit souvent que Mustache est un système de template “logic-less”, car il n’y a pas de if, else ou autre, il n’y a que des tags, que des moustaches :}}

Properly calculating time differences in JavaScript

Let me tell you a tale about a fat-client application that has nice some time-related logic written in JavaScript. We want to calculate the difference between two dates, measured in days. Easy, you say, just use the Date object and do some calculating.

As a JavaScript veteran you know that you have to use new Date() instead of Date() because the second one returns a string for some reason, you recall that the month of October is identified by the number 9 because we start counting the months starting at 0 and quickly figure out that subtracting two Date objects results in a number which is the amount of milliseconds passed between two moments.

var DAY_IN_MS = 24 * 60 * 60 * 1000;
var d1 = new Date(2012, 9, 27);
var d2 = new Date(2012, 9, 28);

console.log((d2 - d1) / DAY_IN_MS); // yields 1

Looks fine, doesn’t it? So just wrap it in a function, unit-test it and be done with it? Not so fast there. Let’s just change the dates ever so slightly

var DAY_IN_MS = 24 * 60 * 60 * 1000;
var d1 = new Date(2012, 9, 27);
var d2 = new Date(2012, 9, 28);
var d3 = new Date(2012, 9, 29);

console.log((d2 - d1) / DAY_IN_MS); // yields 1
console.log((d3 - d2) / DAY_IN_MS); // yields 1.0416666666666667

This is the point where most developers start cursing. Is this a new way in which JavaScript is broken? It isn’t, because the number is completely accurate.

The JavaScript object created by new Date(2012, 9, 28) represents midnight on the 28th of October, 2012 in your local time zonenew Date(2012, 9, 29) represents midnight the following day.

Subtracting the first from the seconds yields the number of milliseconds that have passed between those two moments, which, as you probably have guessed, includes the extra hour put in because of daylight savings time.

> new Date(2012, 9, 29);
Mon Oct 29 2012 00:00:00 GMT+0100 (CET)
> new Date(2012, 9, 28);
Sun Oct 28 2012 00:00:00 GMT+0200 (CEST)
> (new Date(2012, 9, 29) - new Date(2012, 9, 28)) / 60 / 60 / 100
25

So where is the error? The error is in our assumption that a day has 24 hours, because depending on how you define a day, it hasn’t – October 28th 2012 has 25 hours.

If you Google « JavaScript time difference », most people just use Math.round (1) or simply use flat-out buggy code (1 2) and call it a day (pun intended), but that is not how we roll here.

What do we really mean when we ask « How many days have passed between two dates in the calendar »? We usually mean « How many midnights have happened between these two dates? ». Unfortunately, because of DST, you can’t just use the number of milliseconds between two dates at midnight to calculate how many midnights have happened, because some of them are more or less than 24 hours apart. If only there was a magical place that doesn’t have this madness going on…

Luckily, there is, and that place is UTC. UTC is a time measuring system that does not have daylight savings time.

Edit: as pointed out in the comments, the rabbit hole goes down even further – officially, even in UTC, a day might have more than 24 hours because of leap seconds. Fortunately for us, the ECMA-262 specification explicitly ignores leap seconds and we can go about our business. If JavaScript would implement UTC correctly, we would have to account for leap seconds or useUT1.

The JavaScript Date API is just as beautiful as most other JavaScript APIs: While the only useful use of the Date object is by using it as a constructor (with new), the way to use UTC is by using the function Date.UTC which returns a unix timestamp. This is the JavaScript time API in a nutshell:

> new Date(2012, 9, 29);
Mon Oct 29 2012 00:00:00 GMT+0100 (CET) // (a somewhat useful object)

> Date(2012, 9, 29);
'Mon Nov 05 2012 16:18:12 GMT+0100 (CET)' // (a string - no relation to the parameters)

> Date.UTC(2012, 9, 29);
1351468800000 // (unix time in milliseconds)

> new Date.UTC(2012, 9, 29); // failure
TypeError: function UTC() { [native code] } is not a constructor
    at repl:1:9
    [....]

The correct calculation, without using Math.round or other hacks therefore is

var DAY_IN_MS = 24 * 60 * 60 * 1000;
var d1 = Date.UTC(2012, 9, 27);
var d2 = Date.UTC(2012, 9, 28);
var d3 = Date.UTC(2012, 9, 29);

console.log((d2 - d1) / DAY_IN_MS); // yields 1
console.log((d3 - d2) / DAY_IN_MS); // yields 1

These kinds of bugs are sneaky because they only show up for certain input values (I wonder if I would have noticed it if I hadn’t tested the code last week around the DST change) and usually don’t show up in unit tests unless you happen to know what you are looking for. The results are often nearly correct, and we are not used to thinking about time zones and we often hold invalid assumptions about time. Always using UTC isn’t a solution either, because sometimes we want the local time zone to be considered.

Libraries like Moment.js help, but the real protection against these kinds of bugs is to know about time zones, time measurement system and thinking about what you are actually calculating instead of simply throwing a Math.round in there to make it all work.

Just as anybody that has had the pleasure of seeing Rent will tell you: while a year has five hundred twenty-five thousand six hundred minutes, it still is difficult to measure the time of the year.

Useful JavaScript Libraries and jQuery Plugins — Part 2

If you have a problem and need a solution for it, chances are high that a JavaScript library or jQuery plugin exists that was created to solve this very problem. Such libraries are always great to have in your bookmarks or in your local folders, especially if you aren’t a big fan of cross-browser debugging.

In this overview, we feature some of the recent useful JavaScript and jQuery libraries which could be just the right solutions for your common problems. You might know some of these libraries, but you probably don’t know most of them. In either case, we hope that this overview will help you find or rediscover some tools that you could use in your next projects.

Due to the length of this post, we’ve split it into two parts for your convenience:

QUICK OVERVIEW:

Below you’ll find a brief overview and links to the libraries and tools featured in this post.

Text Manipulation Libraries

Prism
A lightweight and extensible syntax highlighter. There are no Prism-specific markup or class names, you can use the standard markup. Prism supports parallelism with Web workers, if available. All styling is done through CSS, with sensible class names like .comment.string.property etc. The overall core core size is only 1.5Kb (minified and gzipped).

Prism

TOC jQuery Plugin: Generate Tables Of Contents
This library automatically generates and guides the user through a table of contents on a page. It’s customizable and is able to automatically highlight a current section of the document. The plugin is also very lightweight, can be used multiple times on a page, and even includes a smooth scrolling functionality for the correct section. The plugin is developed by Greg Allen and is currently available in beta. You might want to check out Tocify jQuery plugin as well.

JavaScript Library

MagicNav: Generates Links for The FAQ
If you want to create a quick navigation for your FAQ page, you can use this jQuery plugin for generating navigation links dynamically from page elements.

Cutter.js
This library solves the problem when cutting content by a number of words is required but you don’t want to change the markup. It simply cuts the content to the required length, while allowing the user to see the full content again.

Trunk8
Trunk8 is a text truncation jQuery plugin that cuts off just enough text from a large block of text to prevent it from spilling over. While conventional truncation just limits the character length, this library is able to measure the content area for spill-over and chooses the text that best fits into a given space.

Relevancy.js
This library allows you to sort an array of items based on their relevancy. This script is attempting to implement basic partial matching which so far has not been successfully implemented. It assigns strings to their respective elements.

Manipulating Tables and Lists

Handsontables: Excel-Like Tables For The Web
This jQuery library allows you to use auto-expanding and auto-complete as well as add new rows and columns. It also includes a legend, scrolling (so as your table grows, it won’t take up your entire page and become unwieldy), context menus, conditional formatting and other features. You can even set it to track changes made to the table. And, all the data you enter in Handsontable can be copied and pasted to Excel, Google Spreadsheet, or LibreOffice.

JavaScript Library

List.js
A cross-browser native JavaScript library that transforms HTML lists into flexible content that you can easily edit. It makes your list easily searchable and sortable. A template-driven concept lets you simply add and edit items.

List.js

Create Nested Sortable Lists With jQuery
This plugin lets you create a sortable list where your users can drag and drop list items into any configuration they choose. You can set various attributes, such as the maximum number of nested levels, as well as setting custom methods (including To hierarchy, To array, and Serialize). As an alternative, there’s also the HTML5 Sortable plugin, which uses HTML5 and jQuery for a similar functionality.

JavaScript Library

Pivot.js
With Pivot you can easily summarize large data sets on the fly. The library lets you create customizable table views from your browser. The results of pivot-table tools (which automatically sort, count, total or give the average) will be displayed as an HTML table pivoting from the input data (CSV or JSON).

Pivot.js

Crossfilter
Crossfilter is a JavaScript library which supports exploring large multivariate datasets in the browser. It enables fast (<30ms) interaction with coordinated views, even with large data sets containing more than a million records. It was built to power analytics for Square Register and allows merchants to slice and dice their payment history fluidly. By using sorted indexes, the library speeds up incremental filtering and thereby increases the performance of live histograms and top-K lists.

Crossfilter

jQuery CSV to Table
This library reads in comma separated values (CSV) or tab separated values (TSV) data and generates an HTML table.

jQuery CSV to Table

Csonv.js
Paul Engel has released a tiny library to fetch relational CSV data client-side (JSON). When using CSV, one file represents one entity; the librarycan also nest relational data within the resulting objects as if you are joining SQL tables.

DataTables jQuery Plug-in
The library can display data from different sources, be it DOM, a JavaScript array, or a server-side file with JSON formatting. Among other features, the library provides pagination, on-the-fly filtering, and multi-column sorting with data type detection. And the features that DataTables provides can be enhanced by many freely available plug-ins: e.g. with row grouping, column filtering, column resizer, etc. The library weighs 68Kb minified, and 20Kb gzip’d. Open source, and released under GPL and BSD.

JavaScript Library

Useful JavaScript Tools for Web Development

Yeoman
Yeoman is a set of tools and libraries that helps to scaffold new projects, automatically compiles CoffeeScript & Compass, runs yours scripts against jshint for proper language coverage and optimizes all your images. It effectively uses plugins like NodeJS, Compass, Grunt and PhantomJS and actually requires the installation of Node 0.8.x.

JavaScript Library

Grunt.js: Task-Based Command Line Tool
Grunt is a task-based command line build tool for JavaScript projects. It has a dozen of predefined tasks built-in already: file concatenation, project scaffolding from a predefined template, validation with JSHint, minifcation with UglifyJS, qUnit tests, server start, running unit tests with nodeunit and running watched files.

Grunt.js: Task-Based Command Line Tool

Holder.js
A client-side image placeholder library to render placeholders entirely in browser. It works both online and offline, and offers a chainable API to style and create placeholders with ease. You can use Holder in different areas on different images with custom themes. Since it extends its default settings with the settings you provide, you only have to include those settings which you want changed.

Holder.js

PxLoader
A JavaScript library that makes it easier to download images, sound files or any other file needed before taking an action on your website. The script lets you set up a preloader for HTML5 games and websites. You can monitor download status and even prioritize downloads in tagged groups.

PxLoader

Percentage Loader
With this jQuery plugin the common horizontal progress bar is displayed differently. The script uses HTML5 canvas and data URI encoding (vector graphics) to allow for visually appealing and variably sizable graphics. Also, it can be used to display feedback during long-running tasks.

Percentage Loader

Resumable.js
The library is designed to introduce fault-tolerance into the upload of large files through HTTP. It thus provides multiple, simultaneous and resumable uploads through the HTML5 File API. That means, losing the networks connection doesn’t require a completely new upload. Users can also manage their uploads without loss of data. However, due to the reliance on the HTML5 File API, support is currently limited to Firefox 4+ and Chrome 11+.

History.js
The library gracefully supports the HTML5 History/State APIs (pushStatereplaceStateonPopState) in all browsers. Including continued support for data, titles, replaceState. Supports jQuery, MooTools and Prototype. You can modify the URL directly, without needing to use hashes.

Jurlp
Jurlp is a jQuery URL parser plugin for parsing, manipulating, filtering and monitoring URLs in hrefand src attributes within arbitrary elements, as well as creating anchor elements from URLs found in HTML or text.

Jurlp

URI.js
To work with URLs you could use this JavaScript library, that offers a jQuery-like API. URI.js offers simple, yet powerful ways of working with query string, has a number of URI-normalization functions and converts relative/absolute paths.

Touchy.js
A JavaScript library which handles touch events without any dependencies. It’s an easy way to assign hand functionality for touchscreen devices to your website. You might want to check outHammer.js as well.

Touchy.js

gridster.js
A jQuery plugin that allows building intuitive draggable layouts from elements spanning multiple columns. You can even dynamically add and remove elements from the grid. It is on par with sliced bread, or possibly better. MIT licensed.

gridster.js

Freetile
A jQuery plugin that enables you to organize the page content in a dynamic and responsive layout. Once applied to a container element, it attempts to arrange its children in a layout that makes optimal use of screen space, by “packing” them in a tight arrangement.

Freetile.js

Strapdown.js
This tool makes it easy for you to embed a Markdown editor into your page. No server-side compilation required. The tool is cross-browser-compatible and has Github-style syntax highlighting.

Strapdown.js

accessifyhtml5.js
Eric Eggert has released a practical polyfill to make HTML5 more accessible. Most modern browsers work fine with HTML5′s new semantic elements, however, they often lack the ARIA accessibility attributes that the specification demands. This small script adds those attributes to enhance accessibility of web sites.

accessifyhtml5.js

jQuery++
An MIT-licensed collection of useful DOM helpers such as jQuery.cookie, jQuery.formParams, jQuery.within and special events for jQuery 1.7 that provide low-level utilities for features that jQuery doesn’t support. You can download a variety of plugins you might wish to use and disregard the rest.

jQuery++

Hogan.js
Twitter’s templating engine that lets you precompile your templates ahead of time for vanilla JavaScript. This engine was developed with Mustache test suite compatibility and performance in mind.

Zepto.js
Zepto is a lightweight JavaScript library with a largely jQuery-compatible API. The main purpose of the library is to cover the most important jQuery functions yet have a relatively small modular library that loads and executes fast, with a familiar and versatile API. If you use jQuery, you already know how to use Zepto. You might want to check Mini.js and CreateJS as well if you are looking for simple and lightweight JavaScript libraries to perform very specific tasks.

Zepto.js

CSSrefresh
A useful small script file that immediately implements changes on your browser made to your CSS-files, by surveying the CSS files in your Web page. Saved CSS-files are executed right away.

CSSrefresh

Has.js
Instead of browser sniffing and feature inference, this library provides a collection of self-contained tests and a unified framework using pure feature detection for whatever library consumes it. Make sure to consider other alternatives, too.

Filepicker.io
An advanced solution for uploading files to the server as well as conversion, synchronization and integration of file uploads with services such as Facebook, Dropbox etc. A free plan is available.

Filepicker.io

XRegExp
An open source MIT licensed JavaScript library, XRegExp provides augmented, extensible regular expressions. The library provides a new syntax, flags, and methods beyond what browsers support natively. Also, take a look at Matches.js, an advanced pattern matching library for JavaScript.

XRegExp

FrameWarp
This library helps you to show pages on your site with a CSS-driven transition effect. It has a helper function which compares the URL of the iframe with the address of the current page. If both the domain and the protocol match, Framewarp will try to access the DOM of the iframe and add the APU methods – one for hiding it, and another one for sending a message to the parent.

Filer.js
Eric Bidelman released a wrapper library for the HTML5 Filesystem API. Filer.js reuses familiar UNIX commands and makes the HTML5 API more approachable for developers that have done file I/O in other languages. Repetitive operations (renaming, moving, duplicating) are easier to manage. You might want to check out DownloadBuilder.js, a library that supports concatenation of local files and uses session storage to cache Ajax/JSONP requests.

Filer.js

Client Side Caching For JavaScript
Server caching is useful for quick response times, but sometimes, especially when you are developing a Web application, you migh need to cache objects client-side rather than server-side. Maybe you need to cache something for offline use, or for reuse later. That’s where locache.jscomes in. It’s a JavaScript caching framework for client side caching in the browser using HTML5 local storage. The library has a memcache-similar API, no dependencies and is very small. And the best part: locache gracefully degrades when the browser doesn’t support local storage. So users with IE6 and IE7 will not get any errors, but as developers say, “caching attempts will be silently dropped and lookups will always appear to be a cache miss.” You can provide an expiration time for cached objects as well.

JavaScript Library

Last Click

ReView.js
This library provides a responsive Web design viewing choice. Users can either “opt-in” or “opt-out” of responsive design states and keep the persistent view preference for each session. Developed in pure JavaScript according to the principles of core (mobile-) first progressive enhancement. You might want to check FlexiNavCalc as well, a responsive navigation library that calculates navigation item widths in percentages to ensure that the navigation holds the layout until a break-point is executed.

JavaScript Library

A Hotline For All Your JavaScript Problems
Do you feel like giving up? Nothing makes sense anymore? Your problems seem insurmountable? Wouldn’t it be great if you could talk to someone who cares and knows your woes? Why don’t you give the friendly, supporting folk at JS Hotline a call when your JavaScript wisdom is at an end? Garann Means created JS Hotline as a helpline for people who are stuck with a JavaScript problem. This call-service powered by Pocket Hotline promises professional help to people who need advice concerning JavaScript. They’ll talk you off the ledge when you just can’t make it work. And it won’t cost you anything but a smile.

JavaScript Library

Useful JavaScript Libraries and jQuery Plugins Part 1

If you have a problem and need a solution for it, chances are high that a JavaScript library or jQuery plugin exists that was created to solve this very problem. Such libraries are always great to have in your bookmarks or in your local folders, especially if you aren’t a big fan of cross-browser debugging.

A JavaScript library isn’t always the best solution: it should never be a single point of failure for any website, and neither should a website rely on JavaScript making the content potentially inaccessible. Progressive enhancement is our friend; sometimes JavaScript won’t load properly, or won’t be supported — e.g. users of mobile devices might run into latency issues or performance issues with some JavaScript-libraries. Often large all-around JavaScript libraries such as jQuery might be an overkill, while tiny JavaScript micro-libraries could serve as good, “light” alternatives for a particular problem. We’ll present some of them today.

In this two-part overview, we feature some of the most useful JavaScript and jQuery librarieswhich could be just the right solutions for your common problems. You might know some of these libraries, but you probably don’t know all of them. In either case, we hope that this overview will help you find or rediscover some tools that you could use in your next projects.

Due to the length of this post, we’ve split it into two parts for your convenience:

QUICK OVERVIEW:

Below you’ll find a brief overview and links to the libraries and tools featured in this post. They are supposed to help you find just the right tool quickly without browsing the whole page.

Web Forms and Input Validation

Select2 jQuery Plugin
A jQuery-plugin for replacement and enhancement of <select>-boxes. The plugin supports search, remote data sets, and infinite scrolling of results. Users can just start typing what they’re looking for. Non-matching entries are removed from the view, and options can be selected using “Enter” or a mouse click. The plug-in works with standard select input fields as well as with multiple selects andoptgroup. It also has support for selecteddisabled and default text (HTML5’s placeholderattribute). The plug-in is based on Chosen, an alternative solution which is currently available in jQuery, MooTools and Prototype flavors and as a Drupal 7 module.

 

JavaScript Library

jQueryCoreUISelect
Another cross-browser solution to enhance the <select> element with jQuery and CSS. Requires jQuery 1.6 or higher. It provides full customization, support of optiongroup, automatic calculations, keyboard support, callback functions and is compatible with mobile devices.

jQueryCoreUISelect

Sisyphus.js
This script allows Gmail-like auto-saving of drafts. It stores form data to the HTML5 local storage of the user’s browser and restores it when the user reloads or reopens the page or opens the page in a new tab. The data is cleared from local storage when the user submits or resets the form.

Sisyphus.js

jQuery Credit Card Validator
This library attaches to the input event (with a fallback to the keyup event) and so every time a number in the input field changes, it calls a validation function. When a card is recognized, the credit card type is highlighted; and if the credit card number is correct, it is highlighted with a green checkmark as well. The plugin supports American Express, Diners Club, Discover Card, JCB, Laser, Maestro, MasterCard, Visa and Visa Electron. You might want to consider credit cards JavaScript validator and the Smart Validate Credit Card Validation plugin.

JavaScript Library

TextExt
This library allows you to transform HTML text into input fields, without resorting to code inflation. The plugin inserts aesthetic as well as practical input possibilities, e.g. Tags, Ajax, Focus and others.

TextExt

Avgrund: Better Modal Boxes
A jQuery plugin for displaying a depth illusion between popup and page. The original script by Hakim El Hattab uses CSS transitions and transformations, and the plugin gracefully degrades in those that do not support transitions and transforms. MIT licensed.

Avgrund: Better Modal Boxes

VisualSearch.js
This library enhances ordinary search boxes with the ability to autocomplete faceted search queries. You can specify the facets for completion, along with the completable values for any facet. You can retrieve the search query as a structured object, so you don’t have to parse the query string yourself.

Ideal Forms Framework
A very comprehensive jQuery plugin for building and validating responsive HTML5 forms. It provides keyboard support, customizable input types, “on the spot” validation, localization and HTML5 placeholder polyfill. Supported in IE8+, Chrome, Firefox, Opera, iOS5+, Android 4.0+.

Ideal Forms Framework

Mailcheck
With this JavaScript spell-checker you can suggests another domain when the user misspells it in an email address. Mailcheck helps effectively reducing sign up typos. While it already includes some  domains, you can easily supply your own.

Mailcheck

Validate.js
A lightweight JavaScript form validation library. You can validate form fields using over a dozen rules and set custom messages; the library doesn’t have any dependencies and you can define your own validation callbacks for custom rules. Works in all major browsers (even IE6!).

JavaScript Library

jQuery File Upload
File Upload widget with multiple file selection, drag&drop-support, progress bars and preview images. It supports cross-domain, chunked and resumable file uploads and client-side image resizing. Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.

JavaScript Library

Grumble.js
This jQuery plugin provides tool tips without being limited to cardinal directions. A grumble can be rotated around a given element at any angle, all 360 degrees and at any distance — with CSS. Works in Internet Explorer 6+ and modern browsers. Also, check Tipped, a larger library of various designs and implementations of tooltips with an extensive API.

Grumble.js

Dialogs for Twitter Bootstrap
A small JavaScript library which allows you to create dialog boxes using Twitter’s Bootstrap modals, without having to worry about creating, managing or removing any of the required DOM elements or JS event handlers. You might want to check out the Date Range Picket for Bootstrap as well as a growing library of HTML Snippets for Twitter Bootstrap.

JavaScript Library

ddSlick
Prashant Chaudhary has realeased a free lightweight jQuery plugin that lets you create a custom drop-down that can include images, a short description, along with your usual text and value. It also supports callback functions on selection. You could use CSS3 Drop-Downs as well.

ddSlick

noty
This jQuery plugin makes it easy to create alert, success, error, warning, information and confirmation messages. The notification can be positioned anywhere on the page and you can customize the text, animation, speed and buttons easily.

noty

jQuery.complexify.js
Complexify helps you to accurately gauge the quality of a user’s password to give them visual feedback, and to enforce a minimum level of security.

JavaScript Library

Numberfy
With Numberfy you can integrate native support for line numbers in your website’s text areas. On every key press in the text area, the text area’s current value is split into lines. This script will not work in IE due to a bug in the text-wrap properties.

FormAccordion
A jQuery plugin for easily hiding and revealing related form fields conditionally.

jQuery.superLabels
You can use the library to give your forms a fade-out label. This implementation makes the label slide across the field when gaining focus and fade out when a value is entered. A fallback is provided as well.

cryptico
An encryption system utilizing RSA and AES for JavaScript.

Web Typography Libraries and Plugins

Baseline.js
A jQuery plugin for restoring baselines thrown off by odd image sizes. To use it, you just call the plugin passing the height of your baseline as a variable. You can also define multiple baselines for different responsive breakpoints.

Baseline.js

FTColumnflow
Developed by the development team of Financial Times, this library is essentially a polyfill that fixes the inadequacies of CSS column layouts. With the library, you can provide configurable column widths, gutters and margins, define elements spanning columns, keep-with-next to avoid headings at the bottom of a column, group columns into pages and standardize line height to align text baseline to a grid.

FTcolumnflow

Responsive Measure jQuery Plugin
A simple script that allows you to pass in a selector (ideally the container where your primary content will go), which generates the ideal font size needed to produce the ideal measure for your text. The script also  generates a resolution-independent font-scale based on the ideal font-size. Created by Josh Brewer.

Baseline.js

The Widow Tamer
The Widow Tamer is a small JavaScript library that automatically “fixes” typographic widows. It’s designed to work with responsive sites, fixing widows as it finds them on resize or orientation change.

JavaScript Library

Fluid Line-Height
With his article, Tim Brown inspired developers to release tools that adjust line-height for optimum readability on responsive websites. The so-called molten-leading binds the height of the line to an element’s minimum and maximum width. jQuery-minLineHeight is a jQuery plugin that works similarly with minimum and maximum width association.

Nice Web Type

FitText.js
This jQuery plugin helps you create scalable headlines that fill the width of a parent element in your fluid or responsive layouts. You might want to check out Lettering.js as well to get a complete down-to-the-letter control of letters in your projects.

FitText.js

Kerning.js
This library lets you kern, style, transform, and scale your Web type with CSS rules, automatically. You can adjust pairings, introduce font conditionals and augment properties.

Kerning.js

SlabText.js
The script splits headlines into rows before resizing each row to fill the available horizontal space. The ideal number of characters to set on each row is calculated by dividing the available width by the pixel font-size – the script then uses this ideal character count to split the headline into word combinations that are displayed as separate rows of text.

Nice Web Type

Little Time-Savers

money.js: Open-Source Exchange Rates and Currency Conversion
Joss Crowcroft has created an Open Source Exchange Rates API, which provides up-to-date, flexible and portable currency-conversion data that can be used in any application, framework or language (not just JavaScript). It has no access fees, no rate limits, no nasty XML: just free, hourly updated exchange rates in JSON. Joss also built money.js, a JavaScript currency conversion library that can be easily integrated in any website. A demo playground and detailed documentation are provided on the website, and the source code is available on GitHub.

JavaScript Library

Accounting.js: Easier Number and Currency Formatting
This simple, tiny JavaScript library will solve your currency and numbers-related formatting hassles, and it even includes optional Excel-style column rendering to line up symbols and decimals. It will make all of your numbers and currencies look much more uniform and professional.

JavaScript Library

Moment.js: Format Dates And Times
Moment.js is a lightweight JavaScript library which lets you format, parse and manipulate dates. You can add or subtract dates from one another, as well as parse things like Unix Timestamps. Display options include formatted dates, time from now, difference, time from another moment, native date and support for leap years.

JavaScript Library

Smart Time Ago
This little jQuery library provides you with an intelligent way of updating relative timestamps in your documents. Smart Time Ago checks and updates every 60 seconds the relative time, within a scope which you specify at the start. It checks the newest time in your scope and tunes the checking time interval to a proper value. The tool can be used as a jQuery plugin, or – if using node – can be installed from npm.

Smart Time Ago

sortByTimeAgo.js
A little JavaScript library that takes an array of objects with TimeAgo properties and sorts them from newest to oldest.

Piecon
Piecon is a tiny JavaScript library for dynamically generating progress pie charts in your favicons. It has been tested to work in Chrome 15+, Firefox 9+ and Opera 11+.

Piecon

Notificon: Favicon Notifications and Alerts
Matt Williams’ Notificon is a JavaScript library for creating favicon alerts and notifications. Instead of having to create a number of favicons and serving them to the client, you can specify a label and a favicon (the default being the current favicon), and it will generate a favicon notification for you. The script currently works with Chrome 6+, Firefox 2+ and Opera, but it’s a nice little add-on for browsers that support it.

jQuery Stick ‘em: Make Content Sticky on Scroll, to a Point
A problem: some of the images in the layout are very tall, so by the time you scrolled down to the bottom of the images, you would have to scroll back up just to read the description of the images or navigation items. The solution: make the content sticky as you are scrolling. This library solves this problem.

jQuery Stick 'em

Countdown.js
Human descriptions for a span of time are often fuzzier than a computer naturally computes. For example, how long does “in 1 month” mean? We casually talk about four weeks, but in fact there is only one month in a year which is four weeks long. Countdown.js tackles this problem by producing an accurate and intuitive description of timespans which are consistent as time goes on.

geolib
A small library to provide some basic geo functions like distance calculation, conversion of decimal coordinates to sexagesimal and vice versa.

Geolib.js

Cookies
Cookies.js is a small client-side JavaScript library that makes managing cookies easy. It caches cookie values, making sequential reads faster, supports AMD / CommonJS loaders and is supported in Chrome, Firefox 3+, Safari 4+, Opera 10+ and Internet Explorer 6+.

firstImpression.js
firstImpression.js is a micro-library (1 Kb minified) that answers the simple question, “Has this user visited this site before?” The detection doesn’t require much logic, so the majority of the code is just a plain JavaScript port of the popular jquery.cookie plugin.

Chirp.js: Tweets on Your Website
A lightweight templating JavaScript library that enables you to display tweets on your website. Client-side caching is available; and you can set if you’d like to show retweets and replies, too.

Chirp.js: Tweets on your website

simpleWeather jQuery Plugin
A simple jQuery plugin to display the weather information for any location. The data is pulled from the public Yahoo! Weather feed via the YQL API.

zip.js
A JavaScript library to zip and unzip files. zip.js provides a low-level API for writing and reading large zip files (up to 4GB with File Writer API). Works with Chrome, Firefox, Safari 6 and (unfortunately) Internet Explorer 10+. With Safari 5 and IE9, you must disable Web Workers and use a Typed Array polyfill.

string.js
A library that provides extra String methods to normalize text strings and manipulate them.

Images, Maps, Graphs and Visualization Libraries

jVectorMap
jVectorMap is a jQuery plugin that renders SVG and VML vector maps in browsers ranging from the ancient Internet Explorer 6 to modern browsers. jVectorMap uses JavaScript, CSS, HTML, SVG or VML, and no Flash or any other proprietary browser plugin is required.

JavaScript Library

Subway Map Visualization jQuery Plugin
If you often deal with government projects, university departments or any websites of sophisticated organizations, every now and again you’ll be asked to design a nice visualization that would explain the various divisions, structures and internal hierarchy of those organizations. Where do you start? Well, creating a Subway Map-alike visualization is an option worth considering.

JavaScript Library

GMaps.js
This library allows you to easily use Google Maps in your projects. Extensive documentation or large amount of code aren’t required anymore. You might want to check out Gmap3 jQuery pluginas well.

GMaps.js

Leaflet: Open-Source Interactive Maps With JavaScript
A library for creating tile-based interactive maps for desktop and mobile browsers. An easy-to-use API is available, and the tool emphasizes usability, performance, flexibility and excellent browser support. The library offers a variety of map layers, including tiles, markers, pop-ups, image overlays and GeoJSON. It supports panning on both mobile and desktop browsers, double-tap zoom on mobile browsers (plus multi-touch zoom on iOS) and more. On iOS, hardware acceleration is enabled, and Leaflet has a modular structure that lets you reduce the size of the library to make it even faster. The project is open source and available for further development and forking on GitHub.

JavaScript Library

SVGeezy: a JavaScript plugin for SVG fallbacks
A JavaScript library which detects SVG images on your website and automatically “looks” for a standard image fallback for those older, less capable browsers. Created by Ben Howdle and Jack Smith.

SVGeezy - a JS plugin for SVG fallbacks

Retina.js
A script that checks each image on your website, when it’s loaded by a user, and replaces low-resolution image with their high-resolution equivalent, if available. It’s assumed that you use Apple’s high resolution modifier (@2x) to designate high resolution versions of images.

JustGage
A JavaScript library for generating and animating gauges. Based on Raphaël library for vector drawing, it’s resolution-independent and works in all modern browsers.

JustGage

arbor.js
A graph visualization library for building trees with connected nodes of data. Arbor.js is essentially a layout algorithm with abstractions for graph organization and screen refresh handling.

Arbor.js

Timeline: Generate Timelines To Visualize Data
This library is supposed to pull in media from different sources. It has built-in support for pulling in data from Twitter, YouTube, Flickr, Vimeo, Google Maps and SoundCloud—and more will be included in the near future. You can easily fill in data from a Google spreadsheet, or use a more detailed method such as JSON to create your time-line. You can also host it on your website by using the Timeline jQuery plugin. The library is available on GitHub, or as WordPress plugin.

JavaScript Library

Unicon
Unicon is a Grunt.js task that makes it easy to manage icons and background images for all devices, preferring HD (retina) SVG icons but also provides fallback support for standard definition browsers, and old browsers alike. From a CSS perspective, it’s easy to use, as it generates a class referencing each icon, and doesn’t use CSS sprites.

Foresight.js
This device recognition library, gives websites the ability to gauge the users device capabilities before the image is requested from the server. Judging display resolution and network speed, it customizes the img src attribute to optimize the websites image resolution to the individual users hardware.

A Magnifying Glass With CSS3 And jQuery
This technique achieves an aesthetically pleasing visual effect. The CSS3 box-shadow and border-radius properties are used to create the magnifying glass itself, while jQuery is used to detect the cursor coordinates and mouse movements and present the larger image. And when your cursor moves off the image, the magnifying glass elegantly fades away. The included tutorial makes it very easy to learn and understand how to achieve this effect. The technique includes both a small and a large image in the markup, so optimizing the technique to load a larger image on demand might be a good idea.

JavaScript Library

Rickshaw
This free and open source JavaScript toolkit provides the elements which you need to create interactive graphs, such as renderers, legends, hovers and range selectors. Rickshaw is based on D3, graphs are drawn with standard SVG and styled with CSS.

Rickshaw

Flot: Plotting for jQuery
A JavaScript plotting library for jQuery, supports Internet Explorer 6+, Chrome, Firefox 2+, Safari 3+ and Opera 9.5+. You can use different types of graphs, use multiple axes, annotate a chart, update graphs with AJAX, provide support for zooming and interaction with the data points, use stacked charts, theresholding the data, apply pie charts and plot prerendered images.

Flot.js

Chronoline.js
Chronoline.js is a library that allows you to create a chronology time-line out of events on a horizontal timescale. From a list of dates and events, it can generate a graphical representation of schedules, historical events, deadlines, and more.

JavaScript Library

Cubism
This D3 plugin helps you to visualize time series and construct better real-time dashboards, pulling data from Graphite, Cube and other sources. Cubism scales and reduces server load by pulling only the most recent values. Cubism can scale easily to hundreds of metrics updating every ten seconds. Cubism’s horizon charts allow you to see many more metrics at-a-glance space than standard area charts.

Cubism

Envision.js
An alternative library for creating fast, dynamic and interactive HTML5 visualizations.

JavaScript Library

Data Visualization JavaScript Libraries
A growing, curated collection of data visualization JavaScript libraries that make it easier to create meaningful and beautiful data visualizations. If you haven’t one a useful data visualization library in the list above, you’ll definitely find the right one in this overview.

Data Visualization JavaScript Libraries

Last Click

jQuery Fundamentals
This HTML book is designed to get you comfortable working through common problems you’ll be called upon to solve using jQuery. You can read the content and try the various interactive examples. Each chapter will cover a concept and give you a chance to try example code related to the concept. Written by Rebecca Murphey and recently updated by her and the rest of the gang at Bocoup.

JavaScript Library

JavaScript Patterns Collection
A JavaScript pattern and anti-pattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM and browser patterns.

JavaScript Library

JavaScript Garden
A growing collection of documentation about the most quirky parts of the JavaScript programming language. It gives advice to avoid common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert JavaScript programmers may encounter on their endeavors into the depths of the language.

JavaScript Library

 

Powerful New CSS- and JavaScript Techniques

Since our last round-up of useful CSS techniques, we’ve seen a lot of truly remarkable CSS geekery out there. With CSS3, some of the older techniques now have become obsolete, others have established themselves as standards, and many techniques are still in the “crazy experimentation” stage.

Since the release of the previous post, we’ve been collecting, sorting, filtering and preparing a compact overview of powerful new CSS techniques. Today we finally present some of these techniques. Use them right away or save them for future reference.

Please note that many techniques are not only CSS-based, but also use HTML5 and JavaScript. We are going to present useful CSS tools and responsive design techniques in separate posts. Please don’t hesitate to comment on this post and let us know how exactly you are using them in your workflow. However, please avoid link dropping; share your insight and experience instead, and feel free to link to techniques that really helped you recently. Thanks to all of the featured designers and developers for their fantastic work!

TABLE OF CONTENTS

  1. CSS Transitions and Animations
  2. Useful and Practical CSS Techniques
  3. CSS Typography and Text Techniques
  4. CSS Navigation Menus and Hover Effects
  5. Visual Techniques With CSS
(Smashing’s side note: Have you already pre-ordered the brand new Smashing Mobile Book? The book features everything you need to know as a designer or developer to create beautiful and rich mobile experiences. Get your book today!)

CSS Transitions And Animations

CSS transitions and animations are often used to make the user experience a bit more smooth and interesting, especially when it comes to interactive effects on hover or on click. Designers are experimenting with technology and create sometimes crazy, sometimes practical—but often innovative techniques which you could use to make your websites just a tiny bit more engaging.

Interactive CSS3 lighting effects
An interesting effect to create interactive lighting effects with 3-D transforms, CSS gradients and masks; the cast shadow was created using box shadows and transforms.

Interactive CSS3 Lighting Effects

CSS3 dodecahedron
A fancy dodecahedron experiment, created using CSS Transforms and a tiny JavaScript snippet.

CSS3 Dodecahedron

CSS 3D Lighting Engine Photon
Our editor Tom Giannattasio has created a JavaScript library that adds simple lighting effects to DOM elements in 3D space using the WebKitCSSMatrix object. It would be great to have an implementation for other rendering engines as well.

CSS 3D Lighting Engine Photon

3D Thumbnail Hover Effects With CSS
This technique produces 3D thumbnail hover effects with CSS 3D transforms. The code is quite verbose and probably could be optimized, but the effect is quite neat.

3D Thumbnail Hover Effects With CSS

Slide In Image Boxes
A technique for creating a “slide in” effect for boxes on hover to make them a bit more interactive.

Slide In Image Boxes

CSS3 bitmap graphics
The bitmap graphics is rendered with CSS: no images, no canvas, no data URIs and no extra markup. The pixels are drawn with CSS gradients, sized precisely to the pixel’s boundaries.

Pure CSS3 Bitmap Graphics

Paperfold CSS
A visual folding effect for hidden comments by Felix Niklas. The plugin takes a DOM element, slices it into parts and arranges them like a folded paper in 3-D space.

Paperfold CSS

Beercamp: An Experiment With CSS 3D
A CSS 3D popup book á la Dr. Seuss. The website was a test to see how far SVG and CSS 3D transforms could be pushed. This is the article about it.

Beercamp: An Experiment With CSS 3D

Covers: A JS / CSS Experiment
Now, that’s quite an experiment: what if we combined a music song, stylesheet and beat detector to create animated… covers? Sure, we can do it with CSS3 and JavaScript! Covers does exactly that. The result is interesting, what can you do with this approach?

Covers: A JS / CSS Experiment

Animation on Apple’s page
John B. Hall explains the CSS animation on Apple’s Web page for the iPhone 4S.

An explanation of the CSS animation on Apple’s iPhone 4S webpage — John B. Hall

Experimental animations for image transitions
A post about experimental 3-D image transitions that use CSS3 animations and jQuery. Only CSS3 transforms are used.

Experimental CSS3 Animations for Image Transitions

Maintaining CSS style states using “infinite” transition delays
This demo allows you to move the character around with the D-pad, and notice how it always keeps its position after you stop moving. This demo doesn’t use any JavaScript. The effect is made possible by using a virtually infinite transition delay, so that the CSS rules never return to their default state. The figure will be stuck in a transition and will move only when you hold down a button.

Maintaining CSS Style States using “Infinite” Transition Delays

CSS 3-D clouds
An experiment in creating 3-D-like clouds with CSS3 transforms and a bit of JavaScript.

CSS3D Clouds

Animated popover of profile box
A technique for an animated profile popover menu, built using CSS transitions.

Animated Profile Popover With CSS

CSS3 scrolling effects
A library of various scrolling effects, such as curl, wave, flip, fly, skew and helix, created with CSS3 and sometimes with JavaScript to spice up the scrolling behavior.

CSS3 Scroll Effects

Spin those icons with CSS3
A simple technique for creating a neat effect that spins social icons with the help of a transform and transition when you hover over them. By Tom Kenny.

Scrolling the Z Axis with CSS 3D Transforms
This article explains how to create the z-scroll effect step by step.

Useful and Practical CSS Techniques

CSS3 Family Tree
Display organizational data or a family tree using just CSS, without Flash or JavaScript. The markup is very simple and uses just nested lists. Pseudo-elements are used to draw the connectors. It also has hover effects: hover over a parent element and the entire lineage will be stylized. Make sure to check Nicolas Gallagher’s Introduction to CSS Pseudo Element Hacks.

CSS3 Family Tree

iOS-style popover
A simple technique for iOS-style custom checkboxes and a subtle hover effect. The technique is a bit buggy but a good starting point in case you need it. Also, check an excerpt from Lea Verou’s talk on customized checkboxes and her article on rule filtering based on specific selector(s) support.

iOS-style Popover

Timeline-Style Comments
Nicolas Gallagher developed a simple and clean technique to present comments in a timeline-alike overview.

Timeline-Style Comments

CSS Table Grid
Here is a nice technique for aligning columns in a table, building a “table grid system” of sorts. The idea is to apply classes to col elements in a table’s colgroup; you always leave one colwithout a class so that it remains fluid and can “soak up” the effects of any breakages elsewhere in the table.

CSS Table Grid

Confirmation Feedback Buttons
This article explains how to create buttons that take on different states depending on the user’s interaction. This type of interaction is especially useful on links such as “Purchase” and “Delete” for which it’s wise to confirm that the user indeed wants to take the specific action. It looks too much like an iTunes button, though.

A calendar in CSS3 and jQuery
A step by step tutorial on how to create a CSS3 calendar with some jQuery animation. Also, check out David Bushell’s responsive calendar demo.

A clean calendar in CSS3 & jQuery : Finishing Touch

Outdenting properties for debug CSS
Let’s assume you are experimenting with CSS or debugging code. You add properties to figure out how things fit together. How often do you forget to remove all of them? A simple technique for this is to mark a CSS property as a temporary or debugging property by outdenting it and putting it at column 0 in the file. A small trick that can save a lot of time.

Outdenting properties for debug CSS

Show Markup in CSS Comments
Chris Coyier discusses the idea of including the basic markup that you will be styling as a comment at the top of your CSS file.

Show Markup in CSS Comments

Selectively displaying data
This technique shows how to selectively display content in a table and add responsive breakpoints to create an responsive, complex multi-column table.

Remove Margins for First/Last Elements
If you ever wanted to remove the top or left margin from the first element in a container, or the right or bottom margin from the last element in a container, you can do this by using pseudo-selectors :first-child and :last-child.

CSS Diagnostics Stylesheet
A very useful snippet to have nearby when you are debugging your CSS or want to find mistakes in HTML.

CSS Diagnostics Stylesheet

Radio Buttons With Two-Way Exclusivity
Learn about the :empty pseudo-class selector and jQuery to ensure that when a radio button is clicked, the area is determined and all other radio buttons in that column are turned off, and then is turned back on when clicked on.

Radio Buttons with 2-Way Exclusivity

Tabbed Navigation With CSS
An elegant tabbed navigation menu with drop-down menus — no JavaScript, of course. Nothing new, but it’s a quite clean solution.

Tabbed Navigation With CSS

Menu With Notification Badges With CSS
A ready-to-use snippet for a navigation menu with notification badges.

Menu with Notification Badges With CSS

Styling based on sibling count (slides)
A fantastic overview of the possibilities for styling based on sibling count. Also, make sure to click through the rest of the slide deck — valuable and useful techniques. Make sure to watchLea Verou’s presentation as well.

Styling based on sibling count (Slides)

Stuff you can do with the “Checkbox Hack”
Wiht the “checkbox hack,” you use a connected label and checkbox input and usually some other element that you are trying to control. Learn what you can do with it.

CSS3 Facebook Buttons
Nicolas Gallagher presents a set of CSS buttons for Facebook with different colors and icons. You might want to check Nicolas’ CSS3 Social Sign-In buttons as well as Free Social CSS3 Buttons that we released earlier as well.

YouTube Popup Buttons
This article explores the default state of YouTube buttons, which have a very subtle bevel but pop up on :hover and :focus states, eager to be clicked.

YouTube Popup Buttons

Centering in the Unknown
When it comes to centering things in Web design, the more information you have about the element being centered and its parent element, the easier it is. Chris Coyier shows how to do it when you do not know anything.

Centering in the Unknown

Uncle Dave’s Ol’ Padded Box
What if you combined background-size: cover and Thierry Koblentz’ intrinsic ratios. The result is images and video than maintain their aspect ratio; but you can also use background-size: cover to change the aspect ratio and auto-cropping of images with just a little CSS. And the great news is that the property is supported in all modern browsers and matches media-query support exactly.

Micro Clearfix: Force Element To Self-Clear its Children
Chris Coyier presents various technique for forcing elements to self-clear its children, including Nicolas Gallagher’s short code snippet from 2011.

Micro Clearfix: Force Element To Self-Clear its Children

Conditional CSS
A clever technique by Jeremy Keith to load additional content conditionally. The idea is that once a media query fires, the content on the body element is generated and can be detected by a JavaScript, prompting extra content to be loaded.

* { box-sizing: border-box } FTW
Once you start mixing and matching various units in CSS — such as % for the container width,em for padding and px for border — then you run right into the box-model problem because the width of the container doesn’t include padding and border. We can easily solve this using box-sizing: border-box. And the best part: it is even supported in IE 8.

Multiple Attribute Values
How to treat multiple values in attributes rather than classes.

Multiple Attribute Values

Diagonal CSS Sprites
If you build a sprite on a diagonal, there will be no components below or to the right of the component you are showing. This allows you to make the element using the sprite as wide or as tall as it needs to be, without worrying about exposing the next component. Also, check outDavid Storey’s article on CSS sprites for the moder era.

Double Click in CSS
Is there a way to detect whether a link is tapped or double-clicked on mobile devices? In fact, we can. However, the code requires some hardcore CSS nerdery. Also, check Pure CSS Clickable Events Without :target by Ryan Collins.

Replacing the -9999px hack (new image replacement)
In the beginning was FIR (Fahrner image replacement). Scott Kellum, design director at Treesaver, has now developed this refactored code for hiding text.

Replacing the -9999px hack (new image replacement)

Fighting the Space Between Inline Block Elements
A series of inline-block elements formatted like you would normally format HTML will have spaces between them. But we often want the elements to butt up against each other, thus avoiding in the case of navigation) those awkward little unclickable gaps. How do you solve it? Chris Coyier has found a couple of solutions.

CSS pointer-events and a pure CSS3 animating tooltip
The pointer-events property allows you to specifiy how the mouse interacts with the element it is touching. See what you can do with it and what to consider when using them.

Anatomy of a mobile-first responsive Web design
An excellent article by Brad Frost about the different considerations for responsive designs. How do you start? What features would you implement and how? What about advanced optimization such as LocalStorage or AppCache? This article provide an excellent guide for getting started with future-friendly responsive designs.

SouthStreet Progressive Enhancement Workflow
A fantastic article by Scott Jehl and Filament Group in which they present a set of tools that form the core of an advanced responsive design workflow. Definitely useful to keep in mind for your next responsive design project.

Typography And Text With CSS

Advanced CSS techniques provide us with remarkable options to style text in very different ways. Not only can we make the typography look sharper and beautiful on the Web with tools such as Lettering.jsKerning.js and FitText; we can also play with glyphs, line breaks, font sizing, truncating text and styling lists. The typography can be adjusted and improved with just a couple of practical approaches.

Interactive Typography effects with HTML5
This techniques uses canvas and JavaScript to create ab interactive typography effect. Users can interact with the glyphs and as designer you can define forms or shapes of the word you’d like to present and how you’d like them to change on hover. Fancy!

Interactive Typography Effects with HTML5

Rocking letters with CSS3 and jQuery
A simple animation of letters with CSS3 and jQuery.

With Rocking Letters into the New Year

CSS 3D Typography
What about integrating stripes into glyphs and adjust the shadow on hover? This technique uses just that, creating a nice, subtle yet engaging visual effect. You can find more interesting type experiments in CSS3type Showcase.

cssandtype.com, gallery of css text effects

cssandtype.com, gallery of css text effects

CSS3 animation and masking text
Chandler Van De Water had a challenge for Trent Walton after seeing the header animation in his “CSS3 in Transition” post. Noticing that he used a PNG image file with knockout transparency, he wanted to do the same CSS animation with selectable text. Trent was happy to oblige! At the moment, this works only in Safari and Chrome.

CSS3 Animations and Masking Text

CSS mask-image and text
Trent Walton uses background-clip: text and mask-image to implement a subtle gray-flecked texture effect over white text. Hover over the box to see how it degrades in unsupported browsers. Make sure to check out Lea Verou’s “Text Masking: The Standards Way” as well.

CSS Mask-Image & Text

Fake bolding of Web fonts
Most browsers simulate bold weights for fonts that do not actually have bold weights. For example, Helvetica Neue Light does not have a bold weight. If you used font-weight: boldwith it, browsers would artificially create a bold weight. This article explains how to avoid fake bolding of Web fonts in your designs. By Divya Manian.

Fake Bolding of Web Fonts

Tomorrow’s Web type today: Say it With a Swash
The excellent series “Tomorrow’s Web type today” by Elliot Jay Stocks provides insights into what will be possible with Web typography soon, e.g. swashes. In fact, you can already use them today if you include a swash subset of a font to achieve the desired effect.

OpenType Swashes

Internationalization Language CSS
A very handy CSS nippet with language-specific quotes. Perfect for international, multilingual projects.

Internationalization Language CSS

Experiments with background-clip: text
With the CSS property background-clip: text, we can add a background image to a text element.

Experiments with background-clip: text

A Call for ::nth-everything
With CSS3, we have positional pseudo-class selectors to help us select a particular element when it has no distinguishing characteristics other than where it is in the DOM in relation to its siblings.

A Call for ::nth-everything

Smooth font using the text-shadow property
A common problem: is there a way smooth the appearance of glyphs on older machines, especially Windows XP (standard / ClearType rendering mode)? Yes, perhaps. You can give a try the text-shadow-property which adds text-shadow on the top-left and the bottom-right to smooth text.


Smooth font using CSS3 text-shadow property

Fluid Type
Trent Walton explains his approach to fluid typography in which he asks himself how we can make sure that browser width and typographic settings such as measure or font-size and how should we handle panoramic viewports? An interesting article, especially if you use a typography-out approach in your designs.

Fluid Type

Pragmatic, practical font sizing in CSS
Harry Roberts shares his thoughts on how to size fonts more efficiently, writing your CSS differently in the process.

Automatic line breaks with CSS3 hyphens and word-wrap
Roger Johansson shows how to solve a common problem: as columns of text become narrower, the risk of a single word being longer than the column’s width increases. When that happens, the text normally extends beyond the column. Luckily, CSS offers two properties to improve the situation: word-wrap and hyphens.

Molten leading (or fluid line height)
When a responsive composition meets a viewport, there are different ways to fill space. Adjusting any one element without also adjusting the others is a recipe for uncomfortable reading, which is one reason why designers have such a difficult time with fluid Web layouts. Tim Brown started a discussion about this issue and provides a couple of techniques for opimization.

Molten leading (or, fluid line-height)

Prevent Long URL’s From Breaking Out of Container
Another snippet by Chris Coyier for keeping long URLs within the container. word-wrapword-break and hyphens properties in use. Also, learn how to Prevent Superscripts and Subscripts from Affecting Line-Height.

Viewport-sized typography
This technique uses new CSS values for sizing elements relative to the viewport’s current size:vwvh and vmin. This allows you to couple the size of, say, a typographic heading to the available screen space. Browser support is quite poor for now, so if you are looking for an alternative, check out FitText.js.

Viewport Sized Typography

Minimum paragraph widths in fluid layouts
This article shows how to solve the problem of paragraphs that are too narrow, by implementing a minimum paragraph width. If the space left a the floating image is less than this width, then the whole paragraph moves below the image.

Styling ordered list numbers
Roger Johansson shows how we can style ordered list numbers with the :before pseudo element, which can take a counter as a value through the content property. Also check outChris Coyier’s post and Louis Lazaris’ CSS Counters: counter-increment and friends.

Styling ordered list numbers

Reverse ordered lists in HTML5
The reverse attribute allows you to write a descending list of numbered items. Louis Lazaris summarizes what it does and offers a solution to get around a lack of browser support for this attribute.

Reverse Ordered Lists in HTML5

Preserving white space with CSS3 tab size
By default, HTML pages ignore anything more than a single space and collapses them. But there are occasions when you’ll want to preserve this space via one of several possible techniques.

Truncating text using only CSS
This code snippet can be used to shorten a line of text using nothing but CSS.

New CSS3 properties to handle text and word wrapping
Louis Lazaris explains the possibilities and problems of text-wrap, overflow-wrap, line-break and word-break, text-overflow and hyphens. Also worth reading: Kenneth Auchenbergdiscusses the options for word wrapping and hyphenation in combination with dynamic width elements.

End Articles with Ivy Leaf
A clever technique for adding an extra touch to the end of your articles. :last-child:afterand content in use.

We are used to classical navigation patterns such as tabbed navigation or drop-downs, but we can do a lot more to spice up our navigation menus with pleasant hover effects, often without extra images. Especially if you’d like to add a bit more polish to your portfolio, gallery or e-commerce website, these techniques can be quite useful. What about “over-the top” hover effect for your links,

Circle Navigation Effect With CSS3
A bubble-like thumbnail preview for your navigation with CSS3.

Circle Navigation Effect with CSS3

Create a CSS3 Image Gallery With a 3D Lightbox Animation
Tom Kenny has extended a CSS lightbox gallery by adding a few hover effects to the gallery grid itself and a 3D rotation to the lightbox content, all with CSS.

Create a CSS3 Image Gallery with a 3D Lightbox Animation – Inspect Element

3D Gallery With CSS3 and jQuery
This article shares an experimental gallery that uses CSS 3D transforms. The idea is to create a circular gallery with an image in the center and two on the sides. Because perspective is being used, the two lateral images will appear three dimensional when rotated.

3D Gallery with CSS3 and jQuery

Creative CSS3 animation menus
Mary Lou presents a couple of creative navigation menu hover effects. The idea is to have a simple composition of elements, an icon, a main title and a secondary title that will be animated on hover using only CSS transitions and animations.

Creative CSS3 Animation Menus

How to spice up your menu with CSS3
Yes, another technique by Tympanus: this tip shows how to spice up a menu by adding a neat hover effect to it. The idea is to slide an image out to the right when the menu item is hovered over.

How to spice up your menu with CSS3

Create a zoomable user interface
David DeSandro reveals how to use CSS transforms to create a zoomable user interface similar to that of Beercamp 2011. In this tutorial, you’ll also learn how to use JavaScript to hijack scrolling to manipulate the zoom.

Create a zoomable user interface with CSS3

Flipboard Navigation
An experimental page layout inspired by Flipboard’s interface.

Flipboard Page Layout

Multi-direction hover
This element shows different hover effects when hovering from different directions.

Multi-direction hover

Experimental Hover Effects
Original and innovative hover effects discovered via Twitter on what appears to be a Japanese code sharing website.

Share JavaScript, HTML5 and CSS

Over-the-top hover effect
A CSS and JavaScript technique for creating an “over-the-top” hover effect using thetransform-origin transform-style properties as well as 3-D transforms.

Accordion With CSS3
Mary Lou experiments with the adjacent and general sibling combinator and the :checkedpseudo-class. Using hidden inputs and labels, she creates an accordion that animates the content areas on opening and closing.

Accordion with CSS3

Expanding Text Areas Made Elegant
An expanding text area is a good choice when you don’t know how much text the user will write and you want to keep the layout compact. In this article, Neil Jenkins explains how to do this simply. Also, you might want to take a look at Textarea Auto Resize, another technique by Louis Lazaris, using a hidden clone element.

Filter Functionality With CSS3
Using the general sibling combinator and the :checked pseudo-class, we can toggle states of other elements by checking a box or radio button. This tutorial explores those CSS3 properties by creating a experimental portfolio filter that toggles the states of items of a specific type.

Filter Functionality with CSS3

An accessible, keyboard-friendly custom select menu
A new approach for more accessibility by Roger Johansson. He styles only the selectelement.

Visual Techniques with CSS

We used to heavily on images and visual elements to create basic visual effects on the Web. With CSS3, we can not only improved the loading speed of the content, but also make our visual elements more flexible and adaptive. Let’s take a look on a couple of examples of how we can achieve that.

Create the Illusion of Stacked Elements with CSS3 Pseudo-Elements
Tom Kenny shows how to create a simple “stacked” look to a group of images.

Create the Illusion of Stacked Elements with CSS3 Pseudo-Elements – Inspect Element

CSS3 Unfold Map with Pins
A handy snippet for placing pins on a map. The code looks a bit verbose, so you might want to remove a couple of visual “nice-to-have” elements.

CSS3 Unfold Map with Pins

Turn Images Into Postage Stamps With CSS3 border-image
Dudley Storey shows a simple way to create a postage stamp from a simple image withborder-image.

Turn Images Into Postage Stamps With CSS3 border-image

Slopy elements with CSS3
Angled shapes and diagonal lines can create an interesting visual flow and add some unexpected excitement. This tutorial shows some simple examples and ways how to create slopy, skewed elements with only CSS.

Slopy Elements with CSS3

CSS Flip Clock
A code snippet for displaying a flip clock-alike time display using CSS.

CSS Flip Clock

CSS3 Image Styles
When applying a CSS3 inset box-shadow or border-radius directly to an image element, the browser won’t render the CSS style perfectly. Here’s a quick tutorial on how to use jQuery to make perfect rounded corner images dynamically. And check out the second part.

CSS3 Image Styles – Part 2

Creating Reusable and Versatile Background Patterns
A simple tutorial on how to create reusable background patterns with Photoshop and CSS.

Creating Reusable & Versatile Background Patterns

Diagonal Graph Paper Gradient
A very nice CSS technique for creating diagonal graph paper gradients using repeating-linear-gradient property in CSS.

Diagonal Graph Paper Gradient

Tucked Corner Effect
A clean CSS technique for producing tucked corners using the pseudo-elements :after and:before as well as data URI-coded images. Also, check out Corner Ribbon Effect with CSS.

CSS Tucked Corner Effect

Scrolling… shadows!
An original technique by Roman Komarov to create CSS-only shadow-scrolling effect usingbackground-attachment: local. Developed by Lea Verou, inspired by Roman Komarov.

Scrolling shadows

Multi-colored CSS progress bars
A quite verbose yet CSS-only solution for displaying multi-colored progress bars. It’s linear-gradient in action! Also, check out CSS3 progress bars that display data inside localized leaderboards for the new analytics platform at G5. They are lightweight and require no JavaScript or images.

Multi-colored CSS Progress Bars

CSS3 breadcrumbs
Learn how to create your own cool CSS3 breadcrumbs. Also, check the CSS Breadcrumbs Example which uses only CSS linear gradients.

CSS3 breadcrumbs

Adobe-like Arrow Headers
A detailed article about the technique Adobe uses to create header bars for modules on its website.

Adobe-like Arrow Headers

Adding a Top Shadow to a website
If you ever wanted to add a shadow along the top edge of the website, you can easily do it by styling body:before.

Adding a Top Shadow to a website

A flexible shadow with background-size
It’s amazing what you can achieve when you combine different techniques—even when facing a challenge such as a flexible shadow. If you had to create an adaptive shadow effect, how would you create it?

Star Ratings With Very Little CSS
Chris Coyier shows how to code star ratings done with very little CSS code and lots of a bit of Unicode madness.

Convert Images to Black And White With CSS
Filters allow us to visually process an image in the browser without needing to go through PhotoShop or use cycle-intensive, script-heavy methods in JavaScript or PHP. CSS3 filters are broadly supported in the most recent versions of Firefox and Chrome, and we can gain support in older versions and alternative browsers — even IE — by using a combination of techniques.

Punching Holes With CSS
A clever and simple technique to make a block in a container appear transparent and display a background image. Also, take a look at Lea Verou’s accessible star rating widget with CSS.

Simple Styles for Horizontal Rules
With the help of a few contributors, Chris Coyier put together this page of simple styles for horizontal rules.

Simple Styles for Horizontal Rules

Optimizing Graphics With CSS Masks
In this video, Aaron Bushnell shows how CSS masks can help make the process easier on you and how to make sure you have fallbacks in place for non-Webkit browsers.

Browser-Specific CSS Hacks
A useful, comprehensive list of browser-specific CSS hacks for targeting legacy browsers. Unfortunately, most of us will need them quite often.

Last Click

CSS3 Lasers!
Shows a laser shot effect when hovering over an element.

CSS3 Lasers!

The DOM Tree
This DOM tree is generated via JavaScript every time you visit the page, so you’ll never see the same one twice. All of the forms are filled with holiday greetings in a variety of languages. CSS3 3D transforms are used to position and rotate, via translate3d() and rotate3d()respectively, the elements when the page loads. The infinitely looping rotation on the tree is controlled by an infinitely looping CSS3 animation. Just one word: crazy!

DOM Tree