I was looking for a way to sort the jQuery DataTables plugin dynamically. I use a simple classname (.datatables) to convert a table into a full featured list manager. Unfortunately not all tables are created the same, so I needed to sort different tables on different columns by default. I found some code in the wild that was..well wild. You can view it at this link - "Dynamic Sorting the Hard Way", I won't post it here because someone might skim what I am saying and snatch up the first code snippet.
First you include this init code and have it run after jQuery has initialized itself. Then you need to add the classes to the table's th tag to define the default sort column and the default sort order.
/* Example HTML
* <table class="datatable">
* <thead><tr><th>ID</th><th>Name</th><th class="default-sort asc">Date</th></tr></thead>
* <tbody></tbody>
* </table>
*/
function InitTables () {
var tables = $('.datatable');
tables.each(function(e,i) {
var index = $('.default-sort',this).length > 0 ? $('.default-sort',this).index() : 0;
var direction = $('.asc',this).length > 0 ? 'asc' : 'desc';
$(this).dataTable({
'bLengthChange': true,
'bPaginate': false,
'sPaginationType': 'full_numbers',
'iDisplayLength': 5,
'bInfo': true,
'bFilter': false,
'aaSorting': [[index,direction]]
});
});
}
Jqueries ValidationEngine is very useful and extremely flexible when you add your own custom validators. Below are a few that I added recently, that the world might find useful.
"ssn": {
"regex": /^\d{3}-?\d{2}-?\d{4}$/,
"alertText": "* Invalid social security number"
},
"zipcode": {
"regex": /^\d{5}$|^\d{5}-\d{4}$/,
"alertText": "* Invalid zip code"
},
"yyyymmdd": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"mmddyyyy": {
"regex": /^(0[1-9]{1}|1[0-2]{1}){1}\W(0[1-9]|(1|2)[0-9]|3[0-1]){1}\W(19[0-9]{2}|2[0-9]{3})$/,
"alertText": "* Invalid date, must be in MM-DD-YYYY format"
},
"money": {
"regex": /^\$?[0-9]+(,[0-9]{3})*(\.[0-9]{2})?$/,
"alertText": "* Invalid currency, must be in $1111.00 format"
}
Transmitting Social Secuirty Numbers over the internet is a process that needs to be secured. There are federal and state laws that restrict the ways that Social Security Numbers can be displayed, transmitted and stored. There are also laws that require disclosure when there is a reasonable belief that an intrusion has occured on a server that stores unencryped personal data. This is not limited to the SSN which should always be encrypted if stored in a database like MySQL, MsSQL or Postgres.
Additionally there are laws that limit the use of credit card numbers in usernames. Michigan for example, prohibits websites from requiring more than four consecutive digits to login when no password is required. This should not be a problem for anyone because we all use passwords for website logins. Right?...
Federal laws restrict who data can be copied to. Most of these laws are industry specific. Look into your specific industry for more information.
When accepting social security numbers (SSN) over the internet it is helpful to think of the three states of the data. Data at rest. Data in transit. Data in storage.
When the data is at rest, ie. displayed to the user, do not display more than 4 consecutive digits.
When the data is in transit, ie. the form is submitted, secure the connection with SSL.
When the data is in storage, ie. saved in the database, encrypt the SSN. Protect all access to the encrypted SSN with login credentials and session management.
Remember that you are protecting personal information and you should take all measures to limit the exposure of this information and protect it from being copied.
References: Govenment Accountability Office - Social Security Number Laws
My blog post (Discovering Binpress) about the binpress.com website was good enough to take first place in their contest! I received an iPad 2 in the mail and it is great. Thank you binpress and the binpress.com community for voting for my submission. It was a great contest with many ups and downs.
Below is a graph showing the results that were posted by Adam Tal along with a great write-up about my post. I look forward to contributing more components in the future.

Tuesday, May 31, 2011
Recently I rediscovered Binpress.com - where you can buy and sell source code. You may remember them from the $40,000 Programming Challenge they had earlier this year. Most serious programmers build complete toolkits for themselves to speed up development, but BinPress makes it cost-effective to purchase these toolkits (or parts of them) for a low cost.
Every programmer has different needs, so here’s how I recommend familiarizing yourself with BinPress and what it has to offer:
Step 1: Discover Binpress
Go through the programming languages on the website and focus on the languages that you program in - for me, it was PHP, PERL, ActionScript and JavaScript. In doing this, I discovered a number of components that I could have used in projects past, and saw that there was room for some of the components that I have created.
Step 2: Get to Know Your Competition
Visit the forums. I found some intelligent people having great conversations about subjects that are dear to me like API's and version control.
Step 3: Become a Member
If you like what you find, create an account. If you are signing up for a seller account, Binpress will review your website, portfolio or code sample to determine your eligibility. They personally review each developer and component and offer buyers a money-back guarantee.
Step 4: Prepare Your Code Submission
If you are approved for membership, submit your code for review. Before you do, make sure you review the Coding Standards and Guidelines. Because I’m a stickler for clean code and structure, my class already met most of the standards - I just needed to do some tweaking and update my documentation.
About My Binpress Submission
The package that I submitted was my PHP Shopping Cart class. It is a stand-alone class built for PHP5 that is mainly for maintaining shopping carts and wishlists, but I have used it for website histories, download lists and briefcases in the past. What I like most about my Cart class is that it is simply a cart and nothing more - it doesn't do calculations or integrate with your ecommerce solution. It’s simple to drop into a project (i.e. no headaches).
Step 6: Determining Code Cost / Value
One of the questions that binpress recommends you ask yourself is :
"Would you would pay for the component you are going to submit?"
My answer is "yes" and, in fact, I would pay more than I am offering it for. I think $9.99 is an excellent price for a tested solution to a common problem like a shopping cart.
Step 7: Package it Up
After you make the code fit for human consumption, you need to package it up and send it. A few recommendations on what to include to make it more marketable:
- Your code - in my case, my Cart Class
- A demo file
- A few test images
- A documentation file - mine was a phpdocumentor file that was generated from the class itself
- A Unit Test - I didn’t do one for the Cart class because it is straight forward. My other classes have Unit Tests.
Step 8: Get Descriptive
Fill out the form with the title, keywords and categories associated with your component. I chose the title DevKen Cart Class so it was descriptive yet namespaced, and I chose keywords that fit the functionality like Cart, Wishlist, Bag and Shopping. The categories I selected were PHP and eCommerce.
On the next page I needed to provide a title and description. I read a blog post by Adam Tal about increasing sales with a better name and summary that demonstrated that being descriptive and providing a useful summary helped customers find your component. I used this opportunity to point out the problems that my class addressed and the reason it is different. Then I provided a link to the demo page and added a usage example with a code sample.
Step 9: Choose a License
Next I created the package and chose the license. I decided on a single site license for $9.99 because I wanted this to be part of a larger package and I'd like users to purchase the other components that make up the full ecommerce backend.
Step 10: Submit Your Code
The final step was to add my source code. I uploaded the zip with their interface and it went through efficiently. At the end of the road here, I can look back and say confidently that it was an easy trip. Setting up my first component and submitting it for review was painless and the interface left little room for mistakes.
In less than 4 hours I got a response back and most of it was positive. The negative was because I didn't run my demo code with error_reporting on. What a bonehead mistake. I fixed the notices and a couple commenting errors and resubmitted it by uploading a new version of the source code.
Only 1 hour later I get a confirmation email saying that the DevKen Cart Class on binpress.com was approved. Sweet. I check it out and it looks great. They even formatted my example code to make it more legible.
Sit Back and Wait for the Money to Roll In.
I have to say my experience with binpress was great. While being pretty new, they already have an impressive list of components. In time we may be looking at the new developer repository.
What we have here is a rather useless and some what detrimental function that will allow you to add an href to any element to make it into a hyperlink. This is detrimental because these links won't be followed by search engines - and useless because it doesn't really add any functionality that can't be accomplished with standard html. It arose out of a need for a table based navigation structure that gave the user feedback in the form of a background color change.
So the syntax is simple - just add an href='#' and MooTools will take care of the rest.
Go To Google
- Go To Google
The other thing that it does is setup the hover status for the element - simply add a class called 'selected' to the css definitions and it will be added to the element on hover over.
And finally here is the function.
/**
* Make any tag into a clickable link. Just give it an href attribute.
*
* @return null
* @access public
*/
function setLinks() {
/* make any non tag with an href into a link */
/* */
var links = $(document.body).getElements('*[href]'); // get the elements with an href
links.each(
function(el,i) {
if(el.get('tag') != 'a' && el.get('class') != 'selected') { // if it is not a tag and it is not currently selected
if(!el.get('lightbox')) el.addEvents( // if it is not a lightbox link
{
'click' : function() {
document.location = this.getProperty('href');
}
}
);
if(!$(el.getProperty('nav'))) { // if it does not have a subnav in the dom
el.addEvents(
{
'mouseover': function(){
el.set('class','selected'); // add the selected class
el.setStyles({'cursor':'pointer'}); // give it a pointer
},
'mouseout' : function() {
el.removeClass('selected');
}
}
);
}
}
if(el.get('class') == 'selected' && el.get('tag') != 'a') selectedNav = el; // identify the link as currently selected so we do not shut it off
}
);
}
Ok.. first the disclaimer. IE sucks and is the root of all of things evil.. I said it.. and I a meant it. Why is it so hard to make background-color accessible through the dom? It isn't - every browser has had it since 1998 - except IE. So if you care about IE as much as I do - here is some code that you can use to easily highlight elements with mooTools on mouseover. This is useful for rows that you want to show the user as clickable. Created a simple to use mootools function for adding mouseover highlighting to your elements. Here is how it works. [cc lang='php']
function setHighlights() {
var hls = $$('*[highlight]');
hls.each(
function(el,i) {
el.store('bg',el.getStyle('background-color'));
el.addEvents(
{
'mouseover' : function() {
this.setStyle('background-color',this.get('highlight'));
},
'mouseout' : function() {
this.setStyle('background-color',this.retrieve('bg'));
}
}
)
}
);
}
Then you need to call it on 'domready'.
window.addEvent('domready', function(){
setHighlights();
});
So you want to create some tabs with mootools, and you figured this has already been done before? Well I couldn't find anything to my liking so I decided to roll my own. Here you will find an easy to use function for creating tabbed content with MooTools 1.2 .
|
Tab1
|
Tab2
|
Tab3
|
|
Tab4
|
Tab5
|
Tab6
|
So create your structure using block elements like
/**
* create a tab structure -
*/
function setTabs() {
var tabs = $$("*[tab]"); // get all the tab links
var selected_tab = null; // the currently selected tab
var selected_tabs = new Hash();
// go through all the found tabs
if(tabs.length > 0) {
tabs.each(
function(el) {
if(!el.getProperty("default_tab")) {
$(el.getProperty("tab")).setStyle("display","none"); // if not hide the contents (though they should be hidden using css already)
} else {
selected_tabs.set(el.get("tab_group"),el);
$(el.getProperty("tab")).setStyle("display","block");
el.addClass("tab_selected");
}
el.set(
{
"events" : {
"mouseover" : function() { // on mouseover set the pointer and give it some style
this.setStyle("cursor","pointer");
this.addClass("tab_selected");
},
"mouseout" : function() { // on mouseout set the cursor to normal and return the style (if it is not selected)
this.setStyle("cursor","normal");
if(selected_tabs.get(this.getProperty("tab_group")) != this) this.removeClass("tab_selected");
},
"click" : function() { // on click hide the current, show the chosen and add some style
if(selected_tabs.get(this.getProperty("tab_group")) != this) {
$(this.getProperty("tab")).setStyle("display","block");
if(selected_tabs.get(this.getProperty("tab_group"))) {
$(selected_tabs.get(this.getProperty("tab_group")).getProperty("tab")).setStyle("display","none");
selected_tabs.get(this.getProperty("tab_group")).removeClass("tab_selected");
}
selected_tabs.set(this.getProperty("tab_group"),this);
}
}
}
}
);
}
);
}
}
Another tip is to create a css class called tab_selected, this will be the class used on mouseover and to show that the tab is selected.
Scrolling through pages of (images in this case).
Creating an animated navigation is one of those things that every developer looks for in their life-time. I know I said to myself - wouldn't it be cool if I could easily create a custom navigation that would work in all browsers, allow me to go atleast 3 levels and be easy to setup. Well let me introduce you to an easy way to accomplish this with mootools. Like my other mootools implementations this one uses custom attributes, so don't expect your code to be valid anymore. Despite this short coming - it is a very useful function. For this to work you will need mootools with the Accordion class. The code below is an example of how the html is setup.
So in the above code I define a few things. First on the first line I define the accordion container by adding an attribute accordion='true'. This tells mootools where to find everything. The next thing that I define in that same element is name of the class that will act as the main link. In this case I named the class 'toggler' - which is the same name as the required attribute. The next thing that I define in the same element is the name of the class that contains the subnav content. In this case I named the class 'element'. So after they are defined I setup the class structure, with the navie on the outside, a button for the main link with a class name of 'toggler' and then the content that will expand when it is clicked called 'element'. Inside of element I go ahead and define another navigation structure so that it has multiple levels. All of the CSS is done in an external css file - the css changes css does is set a style called 'toggler1_selected' on the subnavs when the mouse hovers over it. Finally here is the mootools function.
var active = null;
var subnavs = new Array();
var mainnav = null;
var active_accordion = null;
function setAccordionNav() {
var cords = $(document.body).getElements('*[accordion]'); // get all the navigations (can have more than one) defined by accordion='true'
cords.each(
function (el,i) {
var subs = el.getElements('*[toggler]'); // get all the subnavigations
subs.each(
function(el,i2) {
var pos = null;
var t = el.getElements('.'+el.get('toggler')); // get the subnav togglers
var p = el.getElements('.'+el.get('panes')); // get the subnav elements
pos = t[0].get('pos');
var n = new Accordion(el, t, p,{
opacity: false,
onActive: function(toggler, element){
active_accordion = this;
toggler.addClass('toggler1_selected');
},
onBackground: function(toggler, element){
toggler.removeClass('toggler1_selected');
},
alwaysHide : true,
display: null
});
subnavs.push(n);
}
)
var t = el.getElements('.'+el.get('toggler'));
var p = el.getElements('.'+el.get('panes'));
mainnav = new Accordion(el, t, p, {
opacity: false,
onActive: function(toggler, element){
},
onBackground: function(toggler, element){
element.setStyle('height',element.getSize().y);
},
onComplete:function(toggler, element){
this.elements[this.previous].setStyle('height','auto');
if($chk(active_accordion)) {
active_accordion.display(null); // hide the last child subnav to be opened
}
},
display: null
});
el.setStyle('display','block');
}
);
}
window.addEvent('domready', function() {
setAccordionNav();
});
The function above will look through the dom for elements with an attribute called accordion. Then it will parse them for all of their accordion components. There are many options that you can mess with in this function. Visit the mootools documentation on the accordion class to find out how you can change the function to fit your needs. Example Accordion











