Archive

Author Archive

cross browser shadows and fonts with css only

November 1st, 2009

cross browser css only shadow

If you are like me you probably have have seen a million ways of implementing shadows but none seems really serious. I mean there are quite fancy ways of archiving it. You can use a lot of pictures and wrap the content in a lot of divs. You can use javascript to generate millions of spans/divs to display a smooth shadow with html elements and css colors. You can use canvas (all browser except IE) and VML (IE) for this. And I guess there are even more crazy ways of archiving this.

AS you probably have guessed all these methods are fare from being perfect and pretty complicated to use compared to a css only solution. I’m really surprised that I haven’t seen this solution anywhere else in all my researches.

So how does it work. It’s simple as hell – it’s just css!!

/* the following shadow works in IE5.5-8, FF2-3, Safari3, Chrome */
.shadow {
	box-shadow: 3px 5px 6px #888;
	-moz-box-shadow: 3px 5px 6px #888;
	-webkit-box-shadow: 3px 5px 6px #888;
	filter:progid:DXImageTransform.Microsoft.Shadow(color=#888888, direction=135, strength=7);
}

Using that you get a nice shadow in all browser you currently need (means IE, FF, Safari, Chrome). The IE shadow probably looks a little different however it still way better than no shadow or any fancy above solution (in my opinion).
Make sure to check out the DEMO.

Here is comparison between the css only shadows in IE and the rest:
cssOnlyShadowComparision

cross browser css only fonts

Yet again a quite hard to believe mystery. I always thought that using custom fonts on my webpage is next to impossible. And looking at some quite complex technical solutions like:

I was pretty sure there was no easy solution to this problem. Guess what I just found a “css only” solution.

All you need is a *.eot (IE) and a *.ttf (rest) file of your desired font. You can get a bunch of fonts in these formats at http://www.fontsquirrel.com/. All fonts you can find there are 100% free for commercial use. If you want to use a non free front where you can’t get those 2 required formats you can still use on of the above methods.
After you have those two files you simple need to add this css

/* get fonts from: http://www.fontsquirrel.com/ */

@font-face {
	font-family: 'Bloody Normal';
	/* IE */
	src: url('fonts/BLOODY.eot');
	/* for other Browser you can define multiple formats but usually truetype alone is enough */
	src: local('Bloody Normal'), local('Bloody'),
		url('fonts/BLOODY.woff') format('woff'),
		url('fonts/BLOODY.svg#Bloody') format('svg'),
		url('fonts/BLOODY.TTF') format('truetype');
}

@font-face {
	font-family: 'Droid Sans Regular';
	src: url('fonts/DroidSans.eot');
	src: local('Droid Sans Regular'), url('fonts/DroidSans.ttf') format('truetype');
}

h1 { font-family: 'Bloody Normal'; }

Now you can use the font in your css as with the above H1 or you can use it inline with

<p style="font-family: 'Droid Sans Regular';">

This method works again in all tested browsers (Firefox, Internet Explorer, Safari, Chrome).

Just check out the DEMO.

Conclusion

The here provides solutions for shadows and fonts are extremely easy to use and don’t need any complex technical “workaround”. It’s just pure CSS (with specific CSS for each browser group) and still works in all current browsers you need (Firefox, IE, Safari, Chrome). I’m still really surprised to never have heard from this before. Life would have been so much easier if I knew this a year ago. Funny thing is that these solutions work in browser far older than a year. So this solutions could have been used a long time ago but I have never seen it before.

What do you think about these solutions? why aren’t they being used? do people simple don’t know them or is there any problem I didn’t stumbled upon?

daKmoR WebDev , , ,

use MooTools in TYPO3 with MPR

July 31st, 2009

Finally I can present you the combination of my two favorite Open Source Worlds. Meaning MooTools and TYPO3.

MPM comes with a nice TYPO3 Mod where you can look through all the currently installed MooTools Packages with Demos, Doku, Search… all you need to get it working quite fast :)
MPRinTYPO3

So let’s talk about the reason… I mean I’m a pretty lazy guy. I don’t like to do stuff manually if there is any possibility to do it with some sort of automatism. And working on a big TYPO3 site with multiple MooTools Plugins can be quite a pain in the ass. Every Plugins has it’s own MooTools version and tries to include it. They (usually) don’t share a common library or don’t want to require other extensions. I can understand that but it makes my life sometimes harder… and that’s something I don’t like.

So here we come MPR as an TYPO3 extension. Using MooTools whenever you want to – no need to think about dependencies or graphics and that stuff.

First I wanna say I don’t want to offend the authors of rgsmoothscroll – back then it was the best/only way to include MooTools stuff, but now with good use of MPR it could be much easier.

Let’s see a simple example. Maybe you know the extension rgsmoothscroll it gives you the smooth scrolling experience for anchor links within one page. It uses the Plugin SmoothScroll (now Fx.SmoothScroll) from MooTools More. You can seen an example of it at the MPR demo page or in your TYPO3 BE Mod (see Screenshot above). Now let’s take a small look at some of the files in this extension
ext_localconf.php [1 KB] – register plugin
ext_tables.php [1 KB] – register statics
res/mootools-1.11.js [21 KB] – compressed MooTools 1.11
static/constants.txt [1 KB] – statics for transition, mode, duration, fps
static/setup.txt [1 KB] – set options from constants and insert plugin on page.91
pi1/class.tx_rgsmoothscroll_pi1.php [4 KB]

// [...] could use EXT:t3mootools to build a costum core
// include necessary js
$header .=  '<script type="text/javascript" src="'.$this->getPath($this->conf['pathToMootools']).'"></script>';

$header .= '<script type="text/javascript">
	var Page = {
		initialize: function() {
			new SmoothScroll({
				transition: Fx.Transitions.'.$transition.',
				fps: '.intval($conf['fps']).',
				duration: '.intval($conf['duration']).'
			});
		}
	}
	window.addEvent("domready", Page.initialize);</script>';

// include the js in the header
$GLOBALS['TSFE']->additionalHeaderData['rgsmoothscroll'] = $header;

So let’s explain this a little. First we need to get all the need JS this is a MooTools 1.11 so if I want to use the MooTools 1.2 features then I have a little problem as I would need to build my own MooTools version and I would need to check out what’s needed… it’s not real a problem but it’s rather cumbersome. I believe the extension itself should not need to care about the core or MooTools plugin. It should just say I need Smoothscroll and then use it. If the code get’s included on page render or loaded dynamically shouldn’t be it conserns. OK let’s go on – then we have the script block where it starts the SmoothScroll with all options. Again it work but it’s probably not the best way. I mean why give all options – they are already well set in the class itself and if there is another option added in the class you have to mirror it in your extension. Or let’s say an default value get’s changed because the funtion of the class is a little modified you would have to update the extension default also… doubling data isn’t good because you will always have to update at two places… So I believe options should only be set if you want it expliciply. By default it should use the class defaults and not it own default.

So now let’s give the “same” functionality but with the use of MPR.
ext_localconf.php [1 KB]

t3lib_extMgm::addTypoScript($_EXTKEY,'setup','
page.headerData.989 = TEXT
page.headerData.989.value (
	<script type="text/javascript">
		$require(\'Core/Utilities/DomReady.js\');
		$require(\'More/Fx/Fx.SmoothScroll.js\');

		window.addEvent(\'domready\', function() {
			new Fx.SmoothScroll();
		});
	</script>
)
',43);

now what’s that just one file? yeah it’s all you need and in fact I wouldn’t create an extension for that but just for the sake of explaination. All we do is to add a script block somewhere on the page. In this block we say that we want to use the DomReady stuff and the SmoothScroll stuff. The we just start SmoothScroll with the default options. No need to care about any other js stuff. No need to include any core or any other css all the info is inside the “MooTools Packages” itself.
One problem we have with this solution is that if you want to change some options for SmoothScroll you will have to rewrite the whole block… so I guess we need a different solution to the “map MooTools option into TS” problem… but more on this will follow….

So now we see that with MPR it’s pretty simple to use plugins without even using any extension. Just write the script block prepare some html (if needed) and you are done.

daKmoR MooTools, TYPO3

MPR has been split into MPR and MPM

July 1st, 2009

It’s been quite a while. Honestly I didn’t had as much time for MooTools as I wanted. Nevertheless there has been some changes. The most important one is surely that MPR has been split into 2 separate Projects. It consists now of:

  • MPR (MooTools Package Repository)
  • MPM (MooTools Package Manager)

The reason for this change lies in the nature of a Package Repository. First you have the actual data (MPR), secondly you need some local Application to organize these data (MPM) and finally you need an online server (to be build) to store and order these files globally.

To reflect those changes the url got changed to: http://mpm.mooforum.net/Mpm.php

One other important reason for this change is that if you want to use MPR in an existing system like a CMS or a Blog System you most likely just want to write individual Manager for them (maybe based on MPM, but what if your CMS uses something else than PHP?) but MPR can always stay the same as it’s just the data. And by using a generic Package System you easily can distribute your Packages even between different Managers… (ok that’s a future dream but whatever who knows what the future brings.)

And what I’m currently doing is writing demos for MPR Mootools More as there are so many nice functions. I mean every time I look through the documentation or the code I find some nice new stuff. The only problem with that is by just looking at the text – it’s most of the time pretty hard to see what this code is really capable of. Without a good demo even the best code is nothing but just text to lazy people like me *hehe* I need some place to click around or see some stuff moving.

I mean a demo should show the most common usage of a function. I will try to do some blogging about my ongoing work…

daKmoR MooTools

NetBeans PHP ignore folder

May 26th, 2009

As I’m currently write a little more PHP code than usually I may need a “better” IDE for development. I’m not sure if you know NetBeans but it looks pretty promising.

One thing that bugged me from the beginning was that I have a folder “Data” where I write temporary files and NetBeans kept complaining about those files. I though it would be an easy rightlick->ignore folder. Well yeah it wasn’t. It took me about half an hour to find a way to ignore folders in NetBeans PHP.

Here is my solution:
Goto: Tools->Options->Miscellaneous->Files
Edit the Ignore Files Pattern:

^(##INSERT_FOLDER_HERE##|CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!htaccess$).*$

(replace the ##INSERT_FOLDER_HERE## with your folder name [example.: "Data"])
it’s a regular expression so if you know how to handle it -> your lucky; if not try it and/or ask for help

Here is a picture how it could look:
NetBeans ignore folder

daKmoR WebDev ,

MooTools Plugin CanvasOverlay

April 21st, 2009

Uses canvas to dynamically create overlays (with fill, border, glow) for Images with imagemaps

MPR Demo
MPR Docu

it’s basically a jQuery port from:
http://davidlynch.org/js/maphilight/docs/

it doesn’t support IE as it doesn’t have canvas and I didn’t wanted to hack around with VML… :p

daKmoR MooTools , , , , ,

MPR Best Practice – Plugin MultiOverlays

April 19th, 2009

So now we have this local part of MPR to help us using MooTools Plugins. But howto create such Plugins and what should you use…

(bad) Examples

At first let me show you some examples why it’s not so easy currently to work with MooTools. I think the main reason is that it’s pretty hard to use multiple files (js, css, img…) so people try to do everything in ONE file.

Example Milkbox:

Whenever you add it you will automatically add an Event to domready to create a milkbox with the default params… But what if I don’t want to use it on a page, I can’t easily disable it as I would need to edit the file.
[don't get me wrong - milkbox is cool, I'm just saying it might be even better this way...]
It would be nicer if separate in more files:

  • Milkbox.js // class Milkbox – with the milkbox effect
  • Milkboxes.js // class Milkboxes – create multiple Milkboxes and has the logic for “galleries”
  • AutoMilkboxes.js // will require Milkboxes and will add it’s creation to the domready event

With that now we can decide what we want to include. For the “basic” user its just $require( AutoMilkbox ); and people who know can decide if they either want one or multiple milkboxes. However as I said above using 3 files for one plugin without MPR is pretty inconvenient so people don’t do it. [and by inconvenient I mean it's freaking crazy to use 3 script tags for one little plugin - no no no; and yeah we all don't want to build our own script.json for each plugin... (little side kick to the devs..) :p]
Now you can, just use MPR :)

Example clientcide Waiter:

[again, the waiter is cool, but it might be better this way]
As you can see in it’s docs there if you have this ” baseHref: ‘…’ ” which means that if you use the class the image will be by default loaded from this location: http://www.cnet.com/html/rb/assets/global/waiter/waiter.gif I think this is another “hack” around the MooTools policydon’t use more than one file in your Plugin” *hehe offending people here…*.
I mean what happens if this file gets forgotten? server upgrade – do we still need this waiter.gif? no, just delete it… :p ok that might be not the actual process but there is surely the possibility that this file will just vanish without a notice… why not deliver the file with the Plugin?
It would gives me again a few benefits

  • I can easily replace the image to my own (no need to change any js/css; just replace the file)
  • I can define/override the url in my css (if uses as background image) so again no need to change any javascript
  • What if I have multiple image files? I mean if I have a Plugin that uses some images from the cnet server; some from the plugin server; and some from my own server.. pretty hard to maintain right?

use of MPR within the Plugin MultiOverlays

So now let’s take a closer look at a Plugin and a way I think it should be done.

File MultiOverlay.js

$require(MPR.path + 'Core/Fx.Tween/Fx.Tween.js');
$require(MPR.path + 'More/Class.Occlude/Class.Occlude.js');
var MultiOverlay = new Class({
  ...
});

ok, here we define the requirements and the logic for one MultiOverlay. now if you want to use it I need to use it with an id and create the Class instance myself. If you know how it’s easy…

var myMultiOverlay = new MultiOverlay( $('imageWithId') );

File MultiOverlays.js

this file is so short I will post it’s full code here…

$require(MPR.path + 'Visual/MultiOverlays/MultiOverlay.js');
var MultiOverlays = new Class({
	multiOverlays: [],
	initialize: function(elements, options) {
		$$(elements).each( function(el) {
			this.multiOverlays.include( new MultiOverlay(el, options) );
		}, this);
	},
	getMultiOverlays: function() {
		return this.multiOverlays;
	}
});

So what do we get here, it just gives you the possibility to create Multiple MultiOverlay(s)… So now you can give the image(s) a class and for each image it will create a MultiOverlay instance which get’s saved in an array (if you may need it any time later…)

File AutoMultiOverlays.js

again such a short file… here is it’s code…

$require(MPR.path + 'Visual/MultiOverlays/MultiOverlays.js');
var Auto = Auto || {};
window.addEvent('domready', function() {
	Auto.MultiOverlays = new MultiOverlays( '.MultiOverlay' );
});

basically it just creates a new MultiOverlays with a hard coded “default” value… so if you require this file you don’t need to write any javascript code at all, just give the CSS-class to your images and your done! It’s the easiest way you can do it… [here the value get's saved in the Auto variable as I might still want to use it later... the Auto variable is globally here]

So why all this files?

As I said above I think it’s vital to separate logic to where it belongs. And for me that means if I want to have a single MultiOverlay I should be able to. So the logic for Multiple MultiOverlays shouldn’t be in it, as it’s just more stuff I don’t need… :p
And while we are at it, now that we need a Folder for it let’s add the Docu. So now we got demos, docu, Resources(css, images) all in a single Plugin Zip file.
It’s just easy to send it to someone and he get’s everything – I don’t need to explain what css image files he has to manually include… If you have a local MPR you can just install it in the admin area…. (talking about easy… :) )

What do you want to hear next? more MPR best Pratice?

daKmoR MooTools , , , ,

MPR

April 15th, 2009

I now finally have finished my first alpha for the local part of MPR. It should help you to use, create and share MooTools Plugins. For that it uses a well defined folder structure with defined filenames.
I guess I will create a screencast in the near feature…

for now just check out the demo:
http://mpr.mooforum.net/
(make sure to check out the search at the top right!) [no more missing search for docs... :) ]

if you’re interested check out the git project:
http://github.com/daKmoR/mpr/tree/master

I will try to port quite some plugins to MPR (usually it only means finding out the requirements and probably writing some docs/specs…). With that I guess it should be much easier to use multiple plugins.

If you have a Plugin you want to be integrated just send me the zip file.
If you want to see your Plugin inside MPR but you don’t know how – just let me know and I will try to help…

If you want to know more about MPR you can see/read stuff here:
http://www.delusionworld.com/mootools/mpr-preparation-part-1/
http://www.delusionworld.com/mootools/mpr-preparation-part-2/

daKmoR MooTools , ,

General MooTools UI

March 10th, 2009

While I was trying to fully utilize progressive Enhancement I had another idea. Why not separate functionality and layout even while writing javascript/MooTools. That way it would be far easier to create different layouts for the same functionality without the need to reproduce code. Again let’s just look at an example:
simple tabs (my favorite example… :p)

var myTabs = new FlowTabs.inline( $$('.FlowTabs > h4'), $$('.FlowTabs > div') );

If you look at the source you will find an “$require(…);” it’s just the same as including the file directly with script or link tag. You can find more info about that in my previous posts about MPR. So what do we get with this code – It just gives us the functionality and looks pretty shitty, as only the necessary things are defined. Now let’s take at an example where we use the UI. simple ui tabs

UI.render('Plain');

So it looks now a little bit nicer, but that can all be done with CSS – and you are right as if we look at the source of the UI.Plain.Tabs it does nothing – it just includes 2 css files….

$require(MPR.path + 'Ui/Plain/Plain.js');

$require(MPR.path + 'Snippets/Css/Resources/clearfix.css');
$require(MPR.path + 'Ui/Plain/Resources/Plain.Tabs.css');

Ui.Plain.Tabs = new Class({
	Implements: [Options],
	options: {
	},

	initialize: function(options) {
		this.setOptions(options);
	}
});

How boring is that?!?! Seems like we need a little more complicated example. I guess most of you know the MochaUI – how about adopting some style from it…

MochaUI Tabs

mocha ui tabs

$require(MPR.path + 'Ui/Mocha/Mocha.Tabs.js');
UI.render('Mocha');

only those 2 lines changed – we now load a different UI class and render a different theme called ‘Mocha’… so let’s look at it’s functions

initialize: function(tabs, options) {
	this.setOptions(options);
	this.attach(tabs);
},

attach: function(tabs) {
	if ( $type(tabs) == 'string' ) tabs = $$(tabs);
	if ( $type(tabs) == 'element' ) tabs = [tabs];

	tabs.each( function(el) {
		var inside = new Element('span', { html: el.get('html') } );
		el.empty();
		el.grab(inside);
	}, this);
}

It’s again not really funny as it just creates an span inside every tab – we could have easily put this inside the “original” Tab Class. However what if the problem is a little bit more complex and the layout is also quite heavy on it’s own. Wouldn’t it be nice to separate these problems… Yeah I guess with just words you won’t believe me. So I will show you something more complex afterward.
But for now let’s find out how the UI knows what theme to render and with which parameters. For that we need to look at the FlowTabs.inline.js file… at the bottom you will find:

if ( typeof(UI) !== 'undefined' ) UI.registerClass({ 'Tabs': { 'param': '.ui-tab', 'name': 'FlowTabs.inline' } });

So what this does is basically it registers the FlowTabs Class as a Tabs Class with it’s default parameter and it’s name… Now when the UI is rendered it calls UI.theme.Tabs(param) and that’s exactly what we created earlier: “Ui.Mocha.Tabs = new Class({”

So let’s summaries this a little… until now it works like:

  • create all Tabs + Content
  • call the UI Class that will look for predefined classes and it will modify the layout accordingly

That’s pretty straight forward and in many situations this will work pretty well. However what about dynamically created tabs after the initial creation. I don’t know maybe loading with ajax or as a user populates some fields… So my FlowTabs class my support creating these Tabs on the fly but I somehow need to tell the UI that new Tabs are created and they need to be styled.

So now how do we do that:
FlowTabs.inline.js in the attach function (creating of the tabs) we just fire an Event and give it some things to work with:

this.fireEvent('onUiAttach', [el, j-1, content[i], this.tabsContainer]);

now what we need to do is use this onUiAttach Event. For that we just define this.options.refactor

Ui.Mocha.Tabs = new Class({
	Implements: [Options],
	options: {
		refactor: {
			options: {
				onUiAttach: function(el, i) {
					if ( (typeof(UI) !== 'undefined') && ( typeof(UI.Uis.Tabs) !== 'undefined' ) ) {
						UI.Uis.Tabs.attach( $(el) );
					}
				}
			}
		}
	},

If this is provided the UI will either refactor the class (if it hasn’t been instantiated) or it will set it options if the class has already been instantiated. [This doesn't seem to work currently - so note at the end] To detect that we have another function in FlowTabs.inline that will be called on initialize:

registerUi: function() {
	if ( typeof(UI) !== 'undefined' )
		UI.registerClass({ 'Tabs': { 'param': '.' + this.options.ui.tab['class'], 'name': 'FlowTabs.inline', 'class': this } });
}

it’s basically the same as the registration above, only that we now get the param from the option – this will help for example if we want to change the classes of the tabs; with that we don’t need to change them on the Tab creation script and on the Tab UI script… it will be automatically updated on the UI script. And we give the ui as ‘class’ this (that’s pretty important!).

So now with all that it doesn’t matter when the UI [UI.render('Mocha');] is called as:

  • If you call it at the beginning before all the tabs are created it basically does nothing except that it refactors every Class that it might need. So these classes then automatically do the right thing when the Event onUiAttach is fired.
  • If you call it at the end it will create all the necessary layout and set the options for every Class that’s registered so further elements that get attached get the layout automatically.

I still prefer to call the UI at the and as it might need a little bit less performance. [so also note at the end]

FlowWindows

So now let’s go for an more complex example. Let’s talk about windows… I think there are quite a few implementations out there… MochaUI for example – it’s Window Class is really cool. However it’s also really really big. So what if I just want a little div to resize and drag around. I think functionality and UI should be separated. I mean now I needed to write my own class as I didn’t “wanted” to use a complex layout as MochaUI…. the functionality would be great but you can’t get MochaUI Window without the Layout
So basically that’s what I came up: simple windows. (I looked up some things at MochaUI window so it wasn’t that hard… :p)

If you look at it you see:

$require(MPR.path + 'Windows/FlowWindows/FlowWindows.js');
[...]
var myWindows = new FlowWindows( $$('.FlowWindow > h3')[0], $$('.FlowWindow > div')[0] );
myWindows.attach( $$('.FlowWindow > h3')[0], $$('.FlowWindow > div')[0] );

So this just creates all the divs needed for all the handlers to resize, the header, the controlls… all you need for a nice window… but it’s ugly. yeah sure it’s just for functionality no UI at all. Now let’s get some UI – the plain UI is not really something special (again no change with js – just css). To use it – there are just some small differences…

$require(MPR.path + 'Ui/Plain/Plain.Full.js');
[...]
UI.render('Plain');

we include Plain.Full which will give me all available UI elements of Plain – currently Tabs and Windows. In the end we just need to start UI.render …

So now comes the nice stuff, if I want to just change the style of the Tabs and the Windows I don’t need to change any of the Functionality Classes. I just need to change the UI with:

$require(MPR.path + 'Ui/Mocha/Mocha.Full.js');
[...]
UI.render('Mocha');

and we get Mocha Layout for Tabs and Windows.

The Mocha.Windows is a little bit more complicated as it needed a Canvas which gets updated on every size change. But in the end it’s really flexible and the best thing is if you want to change the functionality you don’t have to think (to much) about they layout. Moreover this also works the other way around. It’s far easiere to create just the layout for a specific structure than to create all the functionality…

one other thing that might come in handy is that you can start the UI without any functionality classes….Mocha UI only. The html markup has to be created accordingly by a server scripting language or so… Starting the UI is again pretty simple

$require(MPR.path + 'Ui/Mocha/Mocha.Full.js');
window.addEvent('domready', function() {

	//say we want to use the WindowsUI and the TabsUI
	UI.render('Mocha', {
		'Windows': {
			'param': '.ui-window'
		},
		'Tabs': {
			'param': '.ui-tab'
		}
	});

});

I currently can only think of one rule you need to follow (maybe I get some more ofer time…):

  • include the UI classes always after the functionality classes

Limitation:

  • the setOptions method (if the UI is called at the end) only support options while with refactor you can override and define new functions.

Note at the end:

The setOptions doesn’t seem to work for subclasses if… yeah right if I knew that I would fix it, but for now the UI should be called at the top if you need some complex update functions like for MochaUI Window (for all the other stuff it also works at the end) [I guess the problem lies somewhere in between the UI - fireEvent('onUiInit'); and the UI.Mocha - this.options.refactor.options.onUiInit. If you catch any error - I'm open for suggestions...]

daKmoR MooTools , , ,

progressive vs non-progressive development

February 9th, 2009

Progressive Enhancement will not only help you to support different levels of context – it can also help you during development. So let’s look at an example again (here is an overview).

What we see here is just a simple way of displaying content that might be transformed to tabs.

<div class="FlowTabs">
	<h4 class="Tab">Short Text</h4>
	<div class="TabContent">Lorem ipsum dolor [...]</div>
	<h4 class="Tab">Long Text</h4>
	<div class="TabContent">Sed ut perspiciatis [...]</div>
</div>

The h4 could be the title and the div could be the content. So without any js magic it’s just a header and some content below. It’s clear that the h4 is the header for the following text. It’s just simple.

MooTools Tabs

Now let’s look at the MooTools version. The HTML just remains the same. Some modifications to the css so it’s look a little bit more like tabs. [this is just an example, no style contest.. :p]
The actual javascript is really boring:

window.addEvent('domready', function() {
	$require(MPR.path + 'Tabs/FlowTabs/FlowTabs.inline.js');
	var myTabs = new FlowTabs.inline( $$('.FlowTabs .Tab'), $$('.FlowTabs .TabContent')  );
});

Just include the class and say we should get the tabs from “.Tab” and the content from “.TabContent”. If we wanted you could easily change this. Say we want to use the first h6 as title and the first div as content (without the classes) we only need to change the class call to “new FlowTabs.inline( $$(’.FlowTabs h6′), $$(’.FlowTabs > div’) );”. So we are pretty flexible and can use this in different situation with the same progressive Enhancement functionality. [ok, class creation takes some time - but once you have it it's so nice :) - I wrote this class just as an example for this, but I might release it at some point...]

jQuery Tabs

This was pretty easy right? Let’s assume we we want to change the javascript Framework (for whatever reason). Now this is usually a pretty bad day for us developers – means a lot of work and recreate all that stuff (if we wanna do it right and don’t use 2 Frameworks at the same time). However with progressive Enhancement half the work is already done. The style, the content, multi-language support… – all that is already working. We just need to recreate the behavior. I had no “real” glue about jQuery but I had it done within less than half an hour. Just take a look at the progressive Enhancement version with jQuery.

$('.FlowTabs').prepend('<div class="inlineTabTabs clearfix"></div>');
var tabContainers = $('.FlowTabs .TabContent');
$('.FlowTabs .Tab').each( function(index) {
	$('.inlineTabTabs').append(this);
	$(this).click( function() {
		tabContainers.hide();
		tabContainers.filter(':eq(' + index + ')').show();

		$('.FlowTabs .Tab').removeClass('act');
		$(this).addClass('act');

		return false;
	})
}).filter(':eq(0)').click();

The code may not be the nicest and there a certainly some ways to make it more flexible like we can do this with MooTool classes, but I got it to work within a short time and it looks and feels exactly the same. I would say progressive Enhancement at it best :) . Now you may wonder why I didn’t used the jQuery UI Tabs. It’s for a simple reason – it’s no real progressive Enhancement (in the way I think of it). First the tabs are in a separate ul, li list at the top of all the content. So if you have no javascript all the tab titles will be disconnected from their content. Furthermore the the “headers” (tabs-title) are links and connected with their content through anchors. So this link href=”#myTabContent” will open the tab with the id=”myTabContent”. There are 2 reasons why I don’t like this: First I don’t want to create all this id’s and second why use links? there is no page to go to… ok, it makes partly sense because the “headers” are disconnected with there content, but that’s just an excuse for the first mistake so we certainly can do better right?

ExtJS Tabs

Now I tried to create the same effect with ExtJS, I was quite motivated as MooTools and jQuery went so smoothly. However the closest to progressive Enhancement I could come up with is more or less progressive Enhancement. Let’s take a closer look.

Ext.onReady(function(){
	var tabs = new Ext.TabPanel({
		applyTo: 'FlowTabs',
		activeTab: 0,
		deferredRender: false,
		autoTabs: true
	});
});

Now with this “autoTabs: true” the TabPanel actually looks for ‘<div class="x-tab" title="myTabTitle">’ and create Tabs from it. It’s easy and again I don’t need to write many javascript. However I had to change my HTML so it’s not progressive Enhancement. Furthermore the title for the tab is not well displayed without javascript. Also I included the the 532KB ext-all.js and a 81KB ext-all.css, both minified. This quite some stuff and it doesn’t even let me choose which tabs and content is taken. Wow and yeah it looks different. I didn’t tried to style it accordingly as I had to change my original 4 lines (from the top – [basic]) to those 2 lines:

<div class="x-tab" title="Short Text">Lorem ipsum dolor [...]</div>
<div class="x-tab" title="Long Text">Sed ut perspiciatis [...]</div>

and after the Ext.TabPanel has transformed it to 49(!!) HTML lines. You can either look at the code in firebug or look at this page where you can see the output code. ok, this was a little bit to much for me, so I guess maybe I would need to create my own Ext widget to make it work, but if I need to write my own code I (me personally) wouldn’t choose ExtJS. [I might be completely wrong here, as I don't know Ext well enough. However it seems like it works quite different than MooTools or jQuery]
Update: you can of course create your own script – Thomas Fritz was nice enough to provide an example. So it really just depends on your personal preference what Framework you wanna choose.

non-progressive ExtJS

Now let’s take the other way around. We just start with a Javascript Version by ExtJS.

Ext.onReady(function(){
	var tabs = new Ext.TabPanel({
		renderTo: 'FlowTabs',
		activeTab: 0,
		plain:true,
		defaults:{autoHeight: true},
		items:[
			{title:'Short Text', html: 'Lorem ipsum dolor [...]'},
			{title:'Long Text', html: 'Sed ut perspiciatis [...]'}
		]
	});
});

All the content is in the javascript so we don’t have any html-content that’s sent by the server. All the transformation from the content (JSON to HTML) is done by javascript. If you don’t have javascript you see a white page. It’s so not progressive Enhancement :p. Whenever I want to change content I need to change the javascript (but hey, I don’t need to change the html… :p). I don’t like this way but whatever.

non-progressive MooTools

Here we go, so now we have this start from a non-progressive page. I want to port it to another Javascript Framework. So now where do I start. hmmm yeah right – at the beginning? I don’t have any html I could take as a base. So I need to recreate everything from scratch again. So let’s just do it:

var items = [
	{title:'Short Text', html: 'Lorem ipsum dolor [...]'},
	{title:'Long Text', html: 'Sed ut perspiciatis [...]'}
];

var container = new Element('div', { 'class' : 'FlowTabs' });
$each( items, function(el) {
	container.grab( new Element('h4', { 'class': 'Tab', html: el.title }) );
	container.grab( new Element('div', { 'class': 'TabContent', html: el.html }) );
});

$require(MPR.path + 'Tabs/FlowTabs/FlowTabs.inline.js');
var myTabs = new FlowTabs.inline( container.getElements('.Tab'), container.getElements('.TabContent') );

container.inject( $('FlowTabs') );

ok, I cheated a little. I just create the basic html from above – this time simply with javascript. Strange right? So now I have all this virtual dom element and here comes again a little MooTools magic (sorry for being biased :p). Even though nothing is in the dom, we can still create the object and hand the class the “virtual” items. Afterward we inject only the already modified html.

I didn’t tried to create it again with jQuery as I think it’s just not worth my time. It’s worthless time as progressive Enhancement is just way better. :)

Conclusion

I’m more than ever confident that progressive Enhancement is the way to use javascript. And I just need to quote Jeremy Keith with: “Think about Ajax from the start but don’t implement it until the very end.” I can really recommend the first part of this speak (about the first 20 minutes).
I also believe that there are currently only a few javascript “plugins” around that make use of “real” progressive Enhancement and that’s really sad as it saves time and give your content some sort of universality. Even if all the design all the behavior changes, your true content will always stay the same.

If there where a package based javascript library that would follow true progressive Enhancement with the same amount of features as the current ExtJS framework than I might not need to write this article (if anyone knows something just let me know). I doubt it so I will just try to create such a library (just step by step) and I think the perfect base for something like this is MooTools.

Update: so here we are again – thx to an example from Peter Fritz every Framework just masters all the requirements. So yet again it’s just your personal preference what Framework you choose.

daKmoR WebDev , , , ,

progressive Enhancement

February 5th, 2009

What is progressive Enhancement? (from wikipedia)

Progressive enhancement is a strategy for web design that emphasizes accessibility, semantic markup, and external stylesheet and scripting technologies. Progressive enhancement uses web technologies in a layered fashion that allows everyone to access the basic content and functionality of a web page, using any browser or Internet connection, while also providing those with better bandwidth or more advanced browser software an enhanced version of the page.

So in other words you start with the most basic concept and evolve it with every step (but the basic concept always stays the same). So let’s do an example (there you can see the actual code) [please don't use IE :p]:

Basic

Here we have the basic setup – simple html so even without css and everything the user will still be able to know what’s going on.
As you can see it’s just about providing a Headline + some Help for a bunch of Input fields.

<h4>Server Configuration</h4>
<a href="help.php?id=Server"><span>(Help)</span></a>
<div> Here are a lot of Inputs </div>
<h4>General Configuration</h4>
<a href="help.php?id=General"><span>(Help)</span></a>
<div> Here are a lot of Inputs </div>

CSS Enhanced

So now the HTML is completely the same we just add some CSS. With this it just looks nicer, but if at any time we remove the CSS it still makes sense. However I’m sure most of you know how to handle CSS.

.cssEnhanced h4 { display: inline-block; margin: 10px 0 5px; }
.cssEnhanced a { background: url('img/help.png'); width: 16px; height: 16px; display: inline-block; margin-left: 5px; }
.cssEnhanced a span { display: none; }

JS Enhanced

With a little javascript we can do even more.

$require('jsEnhanced.css'); //load a css with js, so it will only be included if js is enabled

window.addEvent('domready', function() {
	$require(MPR.path + 'Tools/Roar/Roar.js');
	var roar = new Roar();

	$$('.jsEnhanced a').each( function(el) {
		// load all message on startup - could also be done on mouseenter or click (would require a cache check)
		new Request.JSON({
			'url' : el.get('href') + '&ajax=1',
			'method' : 'get',
			onComplete : function(tree, elements, html) {
				el.store('content', tree);
			}
		}).send();

		el.addEvents({
			'mouseenter': function() {
				roar.alert(el.retrieve('content').header, el.retrieve('content').msg );
			},
			'click': function(e) {
				e.stop(); // or return false; as we don't want to go to the page as the info is provided with js
			}
		});
	});  // $$('.jsEnhanced a').each(

});

First at line 1 we load an additional css with javascript to modify the image to show it doesn’t require a click. If javascript is disabled the icon will just stay as it was.

Then we wait for the dom to be ready(3), as afterward we just loop through all jsEnhanced links(7) and request all the messages we will need for this page(9-15). For the Request Url we just us the href from the link and add an ajax=1. By doing this the script that provides the messages will know that we don’t need all the usual html stuff – just the data encoded in json.
After the Request is Complete(12) we just save the output to the link(13). Finally we just add 2 Events to the links. One to display the message on hover(18) and one to stop the default click as we don’t want to see the standalone info page. [Note: we could also reshow the message on click or do something else]

Javascript multi-language support for free

So if you stick to the progressive enhancement you don’t even need to create a multi-language support for javascript on your own. Just create proper html code with your favorite server side programming language. And with proper I mean make the whole page with html first and enhance it afterward. So what do I mean by “get it for free”. Until now the html code has always been the same, just enhanced with css and javascript. So if I just create a multi-language support for html (and you will always need that) I don’t even need to touch my css or javascript as it will then just enhance my different language. So let’s change the html a little:

<h4>Konfiguration des Servers</h4>
<a href="help.php?id=Server&lang=de"><span>(Hilfe)</span></a>
<div>Hier gibt es eine Menge Inputs</div>
<h4>Allgemein Konfiguration</h4>
<a href="help.php?id=General&lang=de"><span>(Hilfe)</span></a>
<div>Hier gibt es eine Menge Inputs</div>

Now it’s some German HTML with links to German help files (or in this case just a config for the script). I didn’t changed any css or js and it still works. So the only reason you need multi-language support in javascript is when you are lazy and don’t want to create proper html/css. I mean even if you have some messages that only make sense if you have javascript – just include them hidden?.

There are only TWO thing I can think of where you might want to have multi-language support in javascript. ONE is validation of inputs on the client and you don’t want to submit the form every time a user changes something so you can provide error messages. However it’s not even a real good exception, as

  1. with ajax request you could submit a form without disturbing the user
  2. you still need a server side validation
  3. you could include the messages as hidden content

TWO would be real javascript applications like a RichTextEditors or drawing canvas/svg – things that won’t display in any way as html.

So I would forgive you if you use multi-language support for javascript in these special cases.

What you can expect next – development comparison progressive enhancement vs non-progressive.

daKmoR WebDev ,