Different var, same subject

Apr 28, 2011 1 Comment
Tagged: , and

I recently tried to do something and I don't know if it is all that good. If somebody has an opinion about it, I would love to hear it.

I have been using the $ suffix for variables that are really jQuery objects. But I keep coming across occurrences that need the real variable, aka not the jQuery one.

So what I tend to do now is something like:

collection : {
$foo : $('.bar'),
foo : '.bar'
}

In this way I can use both the jQuery object easily and the normal variable, like this:

// use the jQuery object
collection.$foo.action()// use the normal object
$('body').find(collection.foo)

What do you think, is this too much or do you use this too?

I am trying to get a better last example, 'cause this ain't all that clear I think...

which one is faster?

Sep 28, 2010 4 Comments
Tagged: and

People, is there anybody who can help me. I am wondering which one is faster...

Calling this several times in a script:

var foo = $(data).find('foo').text();
var bar = $(data).find('bar').text();

Or wrapping it in a function:

var findData = function (data, field) {
var v = $(data).find( field ).text();
return v;
};

And calling that as many times:

var foo = findData(data,'foo');
var bar = findData(data,'bar');

I know that the last solution appeals to me more, maybe 'cause it looks cleaner. But what I am wondering, which is faster?

After reading the comments, I think I'll go for:

var $data = $(data);
var foo = $data.find('foo').text();
var bar = $data.find('bar').text();

Tip of the hat to Codepo8 / Chris

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
};
}();

another jQuery plugin

Jan 11, 2010 0 Comments
Tagged: , and

A nice and small plugin to create a semanticly step list.

Javascript

(function($) {
$.fn.extend({
steps : function() {
$(this).find('li').each( function ( i ){
$(this).prepend('<span class="step">'+(i+1)+'</span>');
})
}
});
})(jQuery);

$('ol.steps').steps();

CSS

ol.steps li { 
float: left;
padding: 5px;
}
ol.steps li span.step {
border: 1px solid red;
-webkit-border-radius: 20px;
-moz-border-radius: 10px;
line-height:18px;
width: 20px;
height:20px;
margin-right: 5px;
display:inline-block;
text-align:center;
color:#fff;
font-weight:bold;
background-color:#f00;
}

example of steps in action