JQuery coding style

Jun 01, 2010 2 Comments
Tagged: , and

jquery logoI was just documenting a whole bunch of scripts and I noticed that my coding style is not so consistent as I like to think. It seems like I am a real person too :). But this put a question in my head, what do most people do if you chain lots of things. All on one line, or each method on it's own line. Mind you, I compress my code when I go live, so size don't matter much, just readability.

So do you like:

	$( 'foo' )
.clone()
.appendTo('#bar')
.find('p')
.removeClass( 'one' )
.find('input, label')
.val('')
.removeClass( 'two' );

Or do you like this one better:

$( 'foo' ).clone().appendTo('#bar').find('p').removeClass( 'one' ).find('input, label').val('').removeClass( 'two' );

Me I do both, in general I go for the one a method way when it's a lot of code and all on one line when it's only three or four things I am chaining. So, although I go for a consistent style in coding, I seem to violate my own principles when I review a project that I (like this one) work on for months. I wonder if this is something that can be prevented by setting strict coding guidelines or that we should accept it, as long as the overal principles are being followed.

After all, this is a project I worked on with several people, over a period of 6 months. In that time, deviations in coding style can occur, but when you follow the overall guidelines it does no harm in my opinion. The thing is that you should not make you coding standards to strict, as people tend to feel that they are in the way of their work, instead of helping them. Me, I am quit relaxed about coding styles, I tend to agree upon a certain naming convention and some common pattern and that is that. Formatting I can do from textmate, so other people's preferences don't bother me as I take over some code or do a review.

So we agree on a naming convention, like all-small-caps or maybe camelCasing or even using_underscores, and we then select for instance the Revealing Module Patter and of we go...

I am curious about your opinion on this. How do you people approach this when you do a big project or product? Do you work with more extensive guidelines or none at all...

I would really like to hear different opinions, as I think that this sort of thing is getting more important by the day...

By the way, I wrote about CSS coding conventions a long time ago... It still holds in my opion

Pagination script for jquery

Apr 20, 2010 0 Comments
Tagged: , and

A small script I wrote to do pagination, sorting and zebra-striping of a list.

As you can see we start of with a ;, in case some sloppy programmer forgot to add it to the end of his function. Than as a first, we set our namespace as the first thing to do as we don't want to pollute the global namespace. The function is being set as a revealing module pattern.

;var pagination = function () {

We start with an object literal named config to contain the common variables, stuff we use more than once. These variables are private to this function only...

	var config = {
// default amount to be shown
defAm : 15,
// radio buttons for sorting
sort : $('#sort input[type="radio"]'),
sortFirst : $('#sort input[type="radio"]:first'),
// several common classes
hidden: 'hidden',
sorted : 'sorted',
active : 'active'
};

We than initiate the function, this is the only thing we make public at the end of this function.

	var init = function ( t ) {
// check the first radio, just in case ( to avoid problems )
config.sortFirst.attr('checked','checked');
// get the visible li's
var amountSort = $( t +' li:visible').length;
// go to the view function.
view(t,amountSort);
// go and initialize the sorting function...
sort(t);
// as a last thing we get and initiate the script to handle the history stuff.
$.getScript('js/jquery.ba-hashchange.min',back(t));
};

We first start with hiding the list items that need not be shown, the next pages so to speak... When we have done that, we go and build the paging stuff..

	var view = function ( t,amountSort ) {
// hide all of the li's other than the ones on the first page.
$(t+' li').removeClass('even');
$(t+' li:visible:even').addClass('even');
// substract 1 to get the correct amount to be shown...
$(t+' li:visible:gt('+(config.defAm-1)+')').addClass( config.hidden );
// go to paging.
paging(t,amountSort);
};

We build the paging stuff and make it work.

	var paging = function ( t,amountSort ) {
// first we clean up all of the old pagination
$('.pagination').remove();
// we than get the amount of pages
var nr = ((amountSort - ( amountSort % config.defAm ))/config.defAm)+1;
// build the paging ul before the sort radiobuttons
$('#sort').before('<ul class="pagination"></ul>');
// loop through the pages, with the cool guy loop
for ( var i = -1; ++i < nr;){
// append a li with an a to the ul.pagination for each page
// and fill it with the correct number
$('ul.pagination').append('<li><a href="#">'+(i+1)+'</li');
}
// make visible that there is an active page.
$('ul.pagination li:first-child a').addClass( config.active);
// if we click on a pagination link
$('ul.pagination a').click( function (e) {
// get the correct page to show
// note the ,10) this makes sure we can't slip into octal mode...
var link = parseInt( $(this).text(),10);
showHide( t, link);
// now we need to enable the back button...
// we do this by setting the location for the hash tag plugin.
window.location = window.location.toString().split('#')[0] + '#pagination' +link;
// we stop the default action of the (fake) pagination link...
return false;
});
};

This function is wat we use to do the showing and hiding. Note the nice and short :) jQuery selector at the bottom.

	var showHide = function (t,link) {
// remove the active class
$('ul.pagination li a').removeClass( config.active );
// make the clicked one active
$('ul.pagination li:nth-child('+(link)+') a').addClass( config.active );
// show all of the li's
$(t + ' li').removeClass( config.hidden );
// hide all of the li's not on the correct 'page'
// :) notice the nice and short jquery selector...
// it's like this: t = the overall container list.
// in there we find the li's without the class sorted = li:not(.sorted)
// either before the number being calculated = :lt('+(link-1)*(config.defAm)+'),
// note that the number comes from the object literal in config and is therefore easily altered.
// or after that = '+t + ' li:not(.sorted):gt('+link*(config.defAm-1)+')')
// and add a class to them...
// this class also comes from config as I use it more than once..
$(t+' li:not(.sorted):lt('+(link-1)*(config.defAm)+'), '+t+' li:not(.sorted):gt('+((link*config.defAm)-1)+')').addClass(config.hidden);
console.log('lt = '+(link-1)*(config.defAm)+' | gt = '+(link*(config.defAm)))
}

Here we do the sorting, by checking a radio button, gettings it's value and using that to show list items with that class and hiding others.

	var sort = function ( t ) {
// on change
config.sort.change( function () {
// remove all of the sorted and hidden classes, thus making all li's visible
$(t+' li').removeClass( config.sorted );
$(t+' li').removeClass( config.hidden );
// get the value of the radio that is checked.
var v = $(this).val();
// if we selected a filtering option
if( !(v == 'nofilter')){
// hide all of the not chosen li's
$(t+' li:not(.'+v+')').addClass( config.sorted );
}
// go to the view function
// the two arguments are the list and the amount of visible li's (before paging)
view( t,$( t +' li:visible').length );
});
};

This small function utilize the hashchange plugin to make the back buttons work when we page through the pages

	var back = function (t) {
$(window).bind( 'hashchange', function(e) {
var hash = location.hash || '#pagination1';
showHide( t, hash.split('pagination')[1]);
// alert('movement...');
});
};

Here we make the init function public.

	return {
init: init
};
}();

Inline JavaScript

Nov 25, 2009 0 Comments
Tagged: and

As we all know, or should know, the usage of inline JavaScript is not done. For various reasons, it blocks the rendering of your page, it is bad for maintenance and so on.

There is however, one notable exception to this rule. Sometimes it can be usefull to know if you have JavaScript enabled, so you can hide certain elements that depend on a user action. For instance, you have a login button that, when clicked, shows you a box for your username and password with a login button. You don't want to hide this with CSS, so you would do that with javascript. Which you have put at the bottom of your html, just as sir Souders ordained. So at document ready the script kicks in and hides the right element. As this is not noticable on a fast site, sometimes the user can see a Flash of Unstyled Content.

So to countermand that, you can set a class on the HTML element to let the CSS know that it has to hide the correct stuff.

<script type="text/javascript">
document.documentElement.className += ' js-on';
</script>

With this in place you can write CSS to rely on the JavaScript and not have a Flash of Unstyled Content. In my opinion this is the only correct usage of Inline JavaScript.

DL abuse

Oct 26, 2009 1 Comment
Tagged: , , , and

As I had quit a few laughs over my so called abuse of <dl> tags in forms, I decided that it was time I showed him what real abuse of dl's was.

So I present to you the ultimate dl abuse page and it's not even in a form

What I do, is instead of building a proper form with a fieldset and legend in it, I put it all in a definition list. Not quit semantically correct, but at least it is proper and valid html. So this is being written;

<dl>
<dt>Form name</dt>
<dd>
<label for="name">Name</label>
<input type="text" id="name" value="Bruce Lawson" />
</dd>
<dd>
<label for="email">Email</label>
<input type="email" id="email" value="bruce-invalid-email-lawson@foo.bar" />
</dd>
<dd>
<input type="submit" id="go" />
</dd>
</dl>

I then recognize my mistake and correct it with a small bit of JavaScript;

var abuse = function () {
var init = function () {
buildform();
transform();
destroy();
};
var buildform = function () {
$('body').append('<form action="index.html"><fieldset><legend></legend></fieldset></form>')
}
var transform = function () {
var leg = $('dt').html();
$('legend').html(leg)
$('dd').each( function() {
var con = $(this).html();
$('fieldset').append('<p>'+con+'</p>')
});
};
var destroy = function () {
$('dl').remove();
}
return {
init:init
};
}();
abuse.init();

Which gave me a proper form, that looks like this:

<form action="index.html">
<fieldset>
<legend>Form name</legend>
<p>
<label for="name">Name</label>
<input type="text" value="Bruce Lawson" id="name"/>
</p><p>
<label for="email">Email</label>
<input type="email" value="bruce-invalid-email-lawson@foo.bar" id="email"/>
</p><p>
<input type="submit" id="go"/>
</p>
</fieldset>
</form>

So my question of the day is this: Is this the ultimate dl abuse, or can you come up with a worse one?

Please not that this is NOT serious and should not be taken as such.

Update

As Molly rightfully noted, this is more JavaScript abuse than dl abuse. So if you have examples of the former, please let me know...

just in time initialization

just in time initialization

Or as we need a catchy name for this: JITI. This is 'cause we all know that we need a catchy name for something to catch up...

Part 1 - the HTML

what is JITI and what is it to you?

It stands for Just In Time Initialization and I first heard about it from PPK. He came in at one of my clients to review my javscript work there and he told me about some stuff he was working on. JITI is a way to utilize the DOM as you API, something to speed up the loading and rendering time of your page.

At anwb.nl/verkeer I have started using it, in order to speed up the page. We used to render the images of for instance the rain radar as we loaded the page (anwb.nl/verkeer ) and hide them with css. If you clicked on the appropriate checkbox we would set a css class on the body and show the image. This all seemed well and good, but a lot of people come to this page for just the traffic information and the traffic information alone. So why should we have them wait for the image they will never see...

JITI to the rescue.

so now instead of loading the image before hand, we only load the location of the image, like this.

<li>location/of/the/image.gif</li>

As we don't actually load the image, this results in no http request or data collected from the server, until we request the image to be shown by clicking the appropriate checkbox. We then let a small bit of javascript change that to:

<li>
<img scr="location/of/the/image.gif" alt="alttext" />
</li>
The point

So why am I so excited about this? It simply means that we wont let the user wait for data he has not requested. He will not wait longer for a couple of features he may never use, only for what he wants to use. And by doing it by utilizing the dom as our api we don't burden the server with this, just the client and he asked for it...

We do a similar thing with the weather information, instead of rendering the html structure we need to show the weather stuff, we only render the data at page load.

so the user gets from the server this:

<li>
<span>136,63,63,105</span>
<div class="weerB" title="licht bewolkt">
licht bewolkt|18.0|zo|2|0.0
</div>
</li>

Breaks added for clarity, the real thing is one big line of code, better yet the whole html code is nearly devoid of white space or breaks.

after checking the box to see the weather we change that into:

<li 
style="top: 136px; width: 63px; height: 63px; left: 105px; position: absolute;">
<div class="weerB" title="licht bewolkt">
<dl>
<dt>licht bewolkt</dt>
<dt/>
<dt>tekst</dt>
<dd>18.0</dd>
<dt>temp</dt>
<dd>zo</dd>
<dt>windrichting</dt>
<dd>2</dd>
<dt>windrichting</dt>
<dd>0.0</dd>
</dl>
</div>
</li>

Sure, we could do all this with a couple of ajax calls, but with this solution we save the server a lot of calls ( this is a page that gets a couple of million visitors a month) and it's faster after the page has been downloaded. Yes the user still has to download a couple of bytes that may not be needed, but only minimal. If the extra data is a lot more, than a ajax call to fetch that data is viable in my opinion but you have to decide what to use on a case by case basis.

I am wondering if I need a part 2 for the javascript, but I would like to hear your opinion on this