Because sharing is caring

jQuery Plugin Development

Posted: September 24th, 2010 | Author: | Filed under: Javascript, JQuery, Web Development | Tags: , , | 4 Comments »

You can write your jQuery plugin as advanced as you please.
This for example, is a jQuery Plugin:

	jQuery.fn.log = function (msg) {
		console.log("%s: %o", msg, this);
		return this;
	};

But the whole jQuery UI Accordion is also a plugin :-)

I went out to write a larger kind of plugin for a website. And I wanted to find a good plugin writing pattern. These links helped:

Most of them agree to extending the jQuery namespace:

(function($) {
    $.fn.myplugin = function(){
        //Stuff here...
    };
})(jQuery);

But I do miss a bit of Object Orientation in most of them.
I decided to take a bit of each, and create my own approach.
I won’t explain it much, it should be understandable with the comments in code:

(function($){
	/**
	** Seperate object. So each element applied with this plugin has an object structure
	**/
	function PluginObject(container,options){
		//I like to keep a reference to the object I'm working on
		var holder = container;
		//Store 'this' as an instance variable. This comes in handy when you want to speak to it as a reference in clickhandlers etc.
		var _self = this;
		this.init = function()
		{
			//initialize UI and data here
		}
 
		this.test = function()
		{
			//This function serves as a demo method that can be called from outside
		}
		this.render = function()
		{
			// Do complicated rendering here
 
			// Trigger the onRender that could be set through the options
			this.trigger('onRender');
		}
		this.init();
	}
	$.fn.myplugin = function(action,options){
		/**
		** 'action' can be an argument for a function to call
		** If no action is defined, and we just start with the options, initialize is called
		**/
		if (typeof(action) == 'object') {
			options = action;
			action = 'initialize';
		}else if(action == undefined)
		{
			action = 'initialize';
		}
		if(options == undefined)
		{
			options = {};
		}
		/**
		** Set, or update the options
		**/
		function setOptions(el) {
			// If any of the options is a function, bind that as an event
			// this can be something like: 'onRender'
			$.each(options, function(event, fn) {
				if (typeof(fn) == 'function') {
					//Unbind the event if it was already bound
					el.unbind(event);
					//Bind the event with the given function
					el.bind(event, fn);
				}
			});
			//Extend the options with the defaults, and the options already saved in the object
			options = $.extend({}, defaults, el.data('shelf.options'), options);
			// Save the options in the object's data
			el.data('shelf.options', options);
		};
		// Default options
		var defaults = {
			width: 	'900px',
			title: 'Cool Stuff'
		};
		/**
		** This is called everytime we do $(..).myplugin(..)
		**/
		return this.each(function(el){
			el = $(this);
			setOptions(el);
			if(action == 'initialize' || el.data('shelf') == undefined){
				// Initialize the object, save it in itself
				el.data('shelf', new PluginObject(el, options));
			}
			// if called like $(..).myplugin('test'), this is called
			if(action == 'test')
				el.data('shelf').test();
			// This will call render(), render will also trigger 'onRender'
			if(action == 'render')
				el.data('shelf').render();
		});
 
	};
})(jQuery);

Do you develop plugins differently? Or got a good link? I would love to hear about it!


Radio Button values in jQuery

Posted: August 27th, 2010 | Author: | Filed under: Javascript, JQuery, Web Development | Tags: , , , , | No Comments »

Getting the values of radio buttons in Javascript can be a bit of a pain in the behind at times.
You’ll have to assign a different ID to each radiobutton, loop over them to see which one is checked, and return that value.
Too much hassle.

However, jQuery selectors to the rescue!
Suppose you have the following radio buttons:

<input type="radio" name="animals" value="Dog" />
<input type="radio" name="animals" value="Cat" />
<input type="radio" name="animals" value="Bird" />

Getting the selected value could be done like so:

$('input[name=animals]:checked').val()

Try it here:

Dog

Cat

Bird

Good luck, hope it helps someone!


Those fancy GMail buttons, with actual buttons!

Posted: August 25th, 2010 | Author: | Filed under: css, Web Development | Tags: , , , | 1 Comment »

After my post about gmail buttons yesterday, my friend Steven started working on that code.

He came up with an improved version of my example, one that works with actual buttons! Let me demonstrate below:

CSS Code:

input[type="button"], input[type="submit"], button {
margin:0 8px 0 0;
padding:2px 6px;
 
text-align:center;
vertical-align:middle;
 
display: inline-block;
white-space:nowrap;
cursor: pointer;
 
outline:none;
color:#000;
border: 1px solid #bbb;
 
-webkit-border-radius:3px;
-moz-border-radius:3px;
border-radius:3px;
 
background: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#e3e3e3));
background: -moz-linear-gradient(top, #f9f9f9, #e3e3e3);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e3e3e3');
 
border-top-color:#ccc;
border-bottom-color:#a0a0a0;
}
 
input[type="button"]:hover, input[type="submit"]:hover, button:hover {
border: 1px solid #636363;
}
 
input[type="button"]:active, input[type="submit"]:active, button:active {
background: -webkit-gradient(linear, left top, left bottom, from(#e3e3e3), to(#f9f9f9));
background: -moz-linear-gradient(top, #e3e3e3, #f9f9f9);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e3e3e3', endColorstr='#f9f9f9');
}

HTML can be any of the following:

<input type="button" value="it's a button" />
<input type="submit" value="it's a submit button" />
<button>It's a button button</button>

See that code in action right here:

The link to Steven’s post: credit goes where credit is due

P.S.:I know the hover border doesn’t work here, it does work where I implemented the buttons. I’ll look at this later

Update: Xavier Bertels from Live Graphics also had a go at the buttons
This is becoming more and more of a team effort, love it!


Those fancy GMail buttons

Posted: August 24th, 2010 | Author: | Filed under: css, Javascript, Web Development | Tags: , , , | 2 Comments »

For a project I’ve been working on, I wanted to use a different kind of button then the normal HTML .

I decided to go for the GMail style button!
They’re really nice:

  • simple HTML
  • still looks like a button (user friendlyness++)
  • has a modern look aswell

It’s been done before by stopdesign.com, but I wanted to do it myself
I went to dive in some Google CSS and came up with the following:
CSS:

.btn{
	margin:0 8px 0 0;
	padding:3px 8px;
	text-align:center;
	vertical-align:middle;
	white-space:nowrap;
	cursor:default;
	outline:none;
	font:arial,sans-serif;
	color:#000;
	border:	1px solid #bbb;
	-webkit-border-radius:3px;
	-moz-border-radius:3px;
	border-radius: 3px;
	background: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#e3e3e3)); 
        background: -moz-linear-gradient(top, #f9f9f9, #e3e3e3);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e3e3e3');
	border-top-color:#ccc;
	border-bottom-color:#a0a0a0;
	cursor: pointer;
	display: inline-block;
	position: relative;
}
.btn:hover{
	border: 1px solid #636363;
}

Now simply make all your buttons like so:

<div class="btn"><span>Cooler button!</span></div>

which gives you this:

Cooler button!

Strong note: These aren’t actually buttons, they can’t really be used as form-submit buttons as they can only respond to Javascript onClick events! My newer post on the real buttons does do this!
Tested in FF 3.6, Chrome 5, IE8


JQuery UI tabs with selected by #location.hash

Posted: August 5th, 2010 | Author: | Filed under: Javascript, JQuery, Web Development | Tags: , , , | No Comments »

I’m using JQuery UI Tabs in an application.
I really love the implementation, never seen anything so easy.

If you want to make sure another tab but the first one is selected on page load, just give the ‘selected’ option like so:

$("#tabs").tabs({selected: 1});

For the second tab in the tabarray (counting starts with 0).

If you want to make your url’s do the following however: http://www.example.com/mytabbedpage.do#gotothistab. There’s no support from JQuery itself just yet.

I found a solution on Rootsmith Inc’s blog.
Especially sami‘s comment helped me:

1
2
3
4
$(’#my_selector’).tabs({
’select’: function(){$(this).index($(document.location.hash));},
‘load’: function(event, ui){document.location.hash = ui.panel.id;}
});

However, applying this loses your default tab.
My solution:

1
2
3
4
5
var selectedtab = 1;
if(document.location.hash!="" && typeof(document.location.hash)!="undefined" && document.location.hash!= null){
	selectedtab = $(document.location.hash).index() - 1;
}
$("#tabs").tabs({selected:selectedtab});

I know, I like to be thorough in my checks ;-)


SCJD URLyBird v1.1.1 Assignment: first notes

Posted: August 4th, 2010 | Author: | Filed under: Java, SCJD | Tags: , , , | 1 Comment »

After successfully completing my SCJP certification (score of 81% thank you very much), it’s time to start my SCJD certification.

This certificate is achieved in two parts:

  • An assignment which requires you to develop an application
  • An essay you must write to prove you were the one who developed the application and not your supersmart neighbour

I recieved my assignment this week and was surprised to find how little descriptive it was. I was expecting at least 5 use-cases, a GUI design, 3 domain classes that are interlinked and connection to an Oracle database or something.
What I received however was a 6 page HTML  file that describes about what it should do, an interface you must implement and a .db file with serialized data.

Today I dove into reading that file extensively. The only thing I can say is: there isn’t one word too much or too little on that page.
I spent about an hour reading, underlining and taking notes and I recommend you to do the same if you’re going to take your SCJD.

Also, I found this great class written by Roberto Perillo that will surely help you along if you’re having trouble figuring out your database structure.

Development Notes

These are the notes I took on my first read.
I will most likely append to these notes as I develop the application along the way as this will server as my checklist for development.

Structure

The application consists of 3 parts as I see it:

  • Client application
  • Server application
  • Database layer

The data is always retrieved from the database layer. However, the client application can either read and write directly to the database file, or do this via a server application
The server application must be able to allow multiple connections (hello multithreading).

User Interface

  • The user interface must be built using solely Java Swing components
  • The user interface must provide functionality to give a lists of all the bookings
  • The user interface must provide functionality to update/add bookings
  • The user interface must provide search functionality on all fields of the database
  • Results of search/booking listings must be presented in a JTable
  • Settings and preferences of the UI must be saved in a file called suncertify.properties

Database

The database is from a given file. The structure of this file must be adhered.

Structure

The structure of the .db file consists of 3 important parts:

  • Information
    • 4 bytes: Magic cookie that identifies this file as being a data file of a certain type (there are different data files for different assignments)
    • 4 bytes that tell you how long each record will be
    • 2 bytes that tell you how many fields each record
  • Structure, repeated for each field
    • 2 bytes that tell you the size of the fieldname (e.g. ’4′ for field ‘name’)
    • n bytes: field name (n being defined in the precious record)
    • 2 bytes: field length
  • Data: structure defined by previous section

The overall structure is given in the assignment, for me it was:

  • Hotel name: name(64)
  • Hotel location: location(64)
  • Room size: size(4)
  • Is it a smoking room: room(1)   (valid values: Y/N)
  • Price: rate(8)   (including currency. E.g $200.00)
  • Date of booking: date(10)  (yyyy/mm/dd)
  • Owner of the booking: owner(8)   (numeric ID for customer of null for still available)

Requirements

The database layer must provide :

  • record locking. This does not mean file locking!
  • Searching on all fields
  • Listing all records
  • Adding and updating records

Server

The server provides network access so multiple clients can work on the same database.

This server can work via Sockets or RMI. When using RMI, you must use JRMP.
I think I will use RMI as it looks like the cleanest solution.

Footnote

These are all my notes for now. I’ll worry about documentation and delivering when I acutally start developping.