By Example (Functions): Expressions vs Declarations
JavaScript is heavily dependent on functions – for scope, code re-use, new objects, etc. My personal style of JS coding has shifted to solely using function expressions. However, there are still cases where a function declaration would be desirable, such as where the input and output of a function is not affected by any external factors.
For example,
function add(x,y) {
return (+x) + (+y);
}
No external factor will ever change the outcome of the above function.
There are already a lot of posts and articles that go into great detail about the differences of function expressions vs declarations. So I’ll leave you with an example that should make you a believer in function expressions –
====================================
Example #1
var tick = (function () {
//Example of function expression + closure
var tock = 0;
return function() {
return ++tock;
}
}());
//It is impossible to alter `tock` other than using tick()
tick(); //1
tick(); //2
tick(); //3
tick(); //4
====================================
Example #2
//Unnecssary global (unless wrapped in another function, such as jQuery's ready function)
var tock = 0;
function tick() {
return ++tock;
}
tick(); //1
tock = 4; //tock is exposed... and can be manipulated
tick(); //5
tock = 6;
tick(); //7
In: Uncategorized
Formatting Dates
I finally got fed up with creating miscellaneous functions for “stringifying” JavaScript dates. So I decided to take care of this problem once and for all by extending the Date object’s prototype to include a format method. It follows PHP’s date() function exactly so you can always use their website as a reference; and, if you already familiar with PHP’s way of formatting date’s then adopting this will be a cinch.
Just include this below script in your page and you are good to go.
Full Version with Comments (14.4 KB)
Examples -
var today = new Date();
today.format('m-d-Y'); //"06-17-2011"
today.format('l, F jS, Y'); //"Friday, June 17th, 2011"
//week of the year
today.format('W') //25
//ISO 8601 format
today.format('c'); //"2011-06-17T20:06:19Z"
Sorting Arrays
Consider a situation where you want to sort an unordered list based on some arbitrary value within the element such as a data- attribute -
- Pentagon
- Triangle
- Hexagon
- Rectangle
Source:
<ul> <li data-sides="5">Pentagon</li> <li data-sides="3">Triangle</li> <li data-sides="6">Hexagon</li> <li data-sides="4">Rectangle</li> </ul>
JavaScript has a native method called .sort(sort_function) that you can use to sort any array. In this case, we can create an array of DOM nodes using jQuery:
// retrieve our list items
// .get() returns the underlying array of native DOM nodes
var items = $('li').get();
// .sort() is part of the items' array object prototype
// we can take advantage of the built-in sorting functionality
items.sort(function(x,y) {
// x & y are two objects in the array being compared
// our sorting algorithm is simple, compare the sides
return $(x).data('sides') > $(y).data('sides') ? 1 : -1;
});
// empty our unordered list and append the items in their new order.
$('ul').empty().append(items);
Our final result is:
- Triangle
- Rectangle
- Pentagon
- Hexagon
In: JavaScript, jQuery
Bytes to a human readable String
I do a lot of file handling on the client-side nowadays since browsers are becoming more capable of doing so such as Firefox 3.6+ with its drag-and-drop capability. Recently, I ran into a scenario where I wanted to display the size of a file back to the user at they time they uploaded it. Assuming your file size is in bytes, here’s a quick and dirty way to produce a human readable string -
function parseSize(size) {
var suffix = ["bytes", "KB", "MB", "GB", "TB", "PB"],
tier = 0;
while(size >= 1024) {
size = size / 1024;
tier++;
}
return Math.round(size * 10) / 10 + " " + suffix[tier];
}
Example input/output-
873 => 872 bytes 1024 => 1 KB 134987 => 131.8 KB 76435687 => 72.9 MB 4550938343 => 4.2 GB etc..
In: Uncategorized
Textarea Size Limit w/ Counter
TEXTAREAs do not have a native way of specifying a maxlength like INPUTs so most developers use a little piece of JavaScript to help them out. In the old days it was added inline and looked a little something like this:
<textarea onkeypress="return (this.value.length < 50);"></textarea>
This would limit your textarea to a max of 50 characters (it doesn’t support limiting copy/paste either but thats besides the point right now).
Nowadays, we need a little more than just something that silently limits our input. We need a counter, we need feedback, we need interaction. So naturally I turned to jQuery and wrote what I consider to be a very lightweight yet powerful plugin for limiting the length of any form field via any input method. Optionally, a HTML element or jQuery selector can be provided to update a counter field.
In: HTML, jQuery
Naming Conventions
I’ve been reading a lot of nettuts++ lately and they always impress me on how thorough they are with their posts. This one that I read I thought was worth sharing. It’s nothing ground breaking but its something that every programmer should read (at least once). It’s about naming conventions; we’ve all been there before, check it out:
http://net.tutsplus.com/articles/general/9-confusing-naming-conventions-for-beginners/
In: C#, Java, JavaScript, PHP
jQuery 1.4.3 brings HTML5 data support
As of jQuery 1.4.3 HTML5 data- attributes will automatically be pulled into jQuery’s data object.
For example, an HTML snippet with data- attributes -
<a href="#" data-fadespeed="1000" data-hidden="true" data-targets="['one', 'two', 'four']">Test</a>
The attributes can be directly accessed using the .data() method, like so:
$('a').data('fadespeed') === 1000;
$('a').data('hidden') === true;
$('a').data('targets')[2] === 'four'
Note that strings are left intact while JavaScript values are converted to their associated value (this includes booleans, numbers, objects, arrays, and null). The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
This officially makes my metadata plug-in obsolete! :)
In: HTML, jQuery · Tagged with: data, HTML5, jquery
HTML5 – localStorage
HTML5 introduces a new technique for storing precious data locally on the client, window.localStorage. It’s part of the HTML5 specification and is already widely supported in most browsers (even Internet Explorer!).
Keep in mind that data being stored on the client is potentially exposed. You wouldn’t want to store anyone’s credit card information, social security number, etc.
Using localStorage is the way you’d access a JSON object:
var store = window.localStorage; //alias store['someValue'] = (new Date()).getTime(); //stores a local timestamp alert(store.someValue) //retrieves the timestamp
Check if a browser supports storing data locally:
if(typeof window.localStorage !== 'object') {
//does not support storing data locally.
}
In: HTML, JavaScript · Tagged with: data, HTML5, javascript, Storage
jQuery Templates by Microsoft
Back in 2008, Microsoft began shipping Visual Studio with the jQuery library already included. Now, Microsoft is showing its full support of jQuery by developing a very crafty jQuery template plug-in. Originally, John Resig built a simple prototype of the plug-in which Microsoft has now extended and transformed into something quite spectacular. Rey Bango recently presented on the current state of the plug-in at a ThinkVitamin jQuery Online Conference on July 12th, 2010. You can find the source code for his demo here.
First, let’s talk about what a (micro) template is exactly. In short, its a fragment of HTML suitable for passing data to which then gets rendered to an HTML document. An example of a three-column row as a template :
<tr>
<td>${Name}</td>
<td>${Phone}</td>
<td>${Email}</td>
</tr>
An example of some JSON data being sent from the server :
{"Name":"John", "Phone":"555-1234", "Email":"john@jqueryrefuge.com"}
And we wind up with…
<tr> <td>John</td> <td>555-1234</td> <td>john@jqueryrefuge.com</td> </tr>
In a quick and dirty sense, that is what templates do, they define an HTML structure for data to be inserted in to. The client/server can communicate much quicker by strictly passing data back to each other. In other words, no HTML markup should ever be passed between the server/client under a template system.
Microsoft’s Template Plug-in – Syntax & Usage
Creating a template is very easy, simple wrap it in a <script> tag like so…
<script id="MyTemplate" type="text/html">
<tr>
<td>${Name}</td>
<td>${Phone}</td>
<td>${Email}</td>
</tr>
</script>
In the plug-in’s current state it is required that the script tag go directly into the document’s <head> section. Also, notice the script type is set to “text/html”.
Next, we’ll predefine our data that is going to be passed into our template.
var data = [
{ Name: "John", Phone: "555-1234", Email: "john@jqueryrefuge.com" },
{ Name: "Tom", Phone: "555-5678", Email: "tom@jqueryrefuge.com" },
{ Name: "Kenny", Phone: "555-9012", Email: "ken@jqueryrefuge.com" }
];
And the jQuery magic to make the call:
$('#MyTemplate').tmpl(data).appendTo('table');
or (just to show you another perspective but I highly prefer the first one)
$('table').append($('#MyTemplate').tmpl(data));
The .tmpl() method accepts a data object (or a data object collection in this case), and returns the HTML markup as the result which when appended to an empty table (w/ headers) would look like this.
| Name | Phone | |
|---|---|---|
| John | 555-1234 | john@jqueryrefuge.com |
| Tom | 555-5678 | tom@jqueryrefuge.com |
| Kenny | 555-9012 | ken@jqueryrefuge.com |
And that is all there is to it! It’s a work in progress still and there is no real eta yet on when it will be completed by the team. There is also a small chance that this may become part of the jQuery core package.
I leave you with a links to a demo page, the download, the proposal, and some extend usage syntax for the plug-in.
Syntax:
//Inserts the variable as is
${var} or {=var}
//Treats the variable as html
{{html var}}
//For each logic
{{each var}}
//Code blocks
{{if (condition)}} ... {{else}} ... {{/if}}
//Call another template inside another so you can nest templates!!
{{tmpl($dataobject) "#TemplateID"}}
More on nesting templates here.
View a demo page here.
Download the plug-in from github.
Microsoft proposal for the plug-in can be found here.
In: HTML, jQuery · Tagged with: dom manipulation, jquery, microsoft, plug-in, templates
Metadata meets Data Selector
This is my first post that I am sharing where somebody else, Jamie Padolsey, has already written the post (why rewrite a great post). At the beginning of June I wrote regarding the metadata plug-in that I had written, between now and then I am using the hell out of it. Then I went looking for an easy way to select data and found Jamie’s new and improved data selector. Now I’ve managed to completely eliminate using expando attributes as well as using the class attribute for what it was intended, CSS. Gotta love clean code. Read on…
In: jQuery · Tagged with: custom selector, data, jquery, metadata, plug-in

