jQuery UI slider

The past few weeks I had a lot of fun playing with jQuery UI for a client. They wanted to replace some elements in an application, sliders and such, with a more accessible solution. For that I turned to jQuery UI, as I had previously introduced jQuery as the standard javascript library for them.

As I started to play with the code I couldn't helped but be impressed by the great work that has been done by the UI team on this project. But as I looked at it more closely I found some things that could be improved.

So here are some of my grieves with it and a possible way to solve them. I am going to concentrate on the slider ( docs / demo ), as it was with that widget that I started to notice some things missing.

The way you use it is in a true jquery fashion nice and unobtrusive, once you have included the correct javascript files (for that see the documentation), you just do:

$("#slider").slider();

And shazaam, #slider has turned into a slider, nice... But, what happens to the input that people provide...

This solution is nothing without javascript, so in my book it is a nono. I can not imagine that I could use this widget on my sony erikkson k800 phone. So accessible it is not, at least not in the way the demo shows us. And as most people will just copy and paste from demo's, most sliders will not be accessible.

So what you say, a slider can never be accessible, rubbish I say. Stick with me and I will show you a very simple way to make this accessible. And in a few day I will put up some example sliders to accompany the code as suggested by Danny Lagrouw.

Improvement

First we will look at what a slider does, it provides a user the possibility to enter data. Whoa, a whole new concept... eh no.

Lets start with an simple < input type="text" /> that gives people a good opportunity to enter a value, no? But what about stepping you say, that we can solve with a few < input type="radio" />. All we have to do is write javascript that sends the value of the slider to the input and when the form is submitted, the server can sort it out.

If a user has no javascript a viable alternative is provided. So not only advantages on the user level, but did you notice that we just solved the data to server problem, in a way that requires us to write zero I admit it is boring but if you want your fancy interface to do something, it has to interface with the back-end as well.

So we start with the html, as that is the base for accessible solutions, we set up a free form slider. As we do this, we make sure that we create a fully functional option for everybody. That is, the purpose of the slider is to set a value.

<div class="slider free" id="slider">
<label for="text">
label
</label>
<input type="text" id="text" />
</div>

As you see a nice and clean solution where data can be entered and processed. What we miss is the fancy slider, which we will create with javascript like this:

// add a slider container div
// add a slider handle to slider container
// place a span to recieve the value
// and add a class to the container
// find and set the input to readonly
jQuery('.slider')
.append('<div class="slideContainer"> // br
<div class="ui-slider-handle""> // br
</div> // br
</div> // br
<span class="value"></span>') //br
.addClass('sliding') // br
.find('input').attr("readonly","readonly");
// linebreaks (br) added for readability

There you have it, an accessible solution for a slider, simple as that.

But wait, what if I have 5 steps that I want people to choose from. That I cannot do, so your solution sucks and I still am stuck with a pure javascript solution says the sceptic (I know who you are...). Oke, the second one is a slider with steps for you.

First let us see what that is, it is simply a option you choose from a limited number of options isn't it. The html solution for this is really easy, radio buttons. So of we go with html

<div class="slider steps" id="slider2">
<fieldset class="radios">
<legend>legend</legend>
<input type="radio" name="radio" value="0" id="v0" />
<label for="v0">zero</label>
<input type="radio" name="radio" value="1" id="v1" />
<label for="v1">one</label>
<input type="radio" name="radio" value="2" id="v2" />
<label for="v2">two</label>
<input type="radio" name="radio" value="3" id="v3" />
<label for="v3">three</label>
<input type="radio" name="radio" value="4" id="v4" />
<label for="v4">four</label>
</fieldset>
</div>

Just like that we have a viable and accessible solution in plain old semantic html, now for the javascript.

var sliderSteps = {
radiobuttons : ((jQuery(this) //br
.find('input[type="radio"]') //br
.length)-1) //br
.toFixed(0),
init : function(targ){
sliderSteps.createSlider(targ);
sliderSteps.set(targ)
},
set : function(targ){
var w = (100/((sliderSteps.radiobuttons*1)+1));
jQuery(targ) //br
.find('label, .ui-slider-handle') //br
.width(w+'%');
},
createSlider : function(targ){
jQuery(targ).slider({
// zoveel stappen als er radio button zijn...
steps : sliderSteps.radiobuttons,
change:function(e,ui){
var x = jQuery(this).slider('value');
var a = (x/100*((jQuery(this). //br
find('input[type="radio"]').//br
length)-1)).toFixed(0);
// set the value somewhere...
jQuery(this).find('.value').text(a);
// check the radiobutton.
var t = jQuery(this). //br
find('input[@type="radio"]')[a];
jQuery(t).attr('checked','true');
}}
);
}
}
sliderSteps.init('#slider2.steps');
// linebreaks (br) added for readability

So there you have it, a nice clean and accessible slider solution for the folks at jquery ui to include in their demos. And for everybody else to look at and maybe even use. So have fun with it and let me know if you like it.

If you see any faults in the code please let me know, but as I am on holiday now, don't except me to rush...

Here is all the demo code zip file wn.slider.zip for you to play with.

Technorati Tags:, , ,

Hidden advantage of event delegation

Jun 15, 2008 4 Comments
Tagged: , , and

Nowadays, everybody has (or should) heard of event delegation, the new gray in javascript. It has many advantages, such as cutting down on the event handlers javascript needs to set on a page. But there is one advantage, that not many people talk about. So I will.

First we will start with the most talked about stuff, to refresh your memory, or to give you a short introduction in the matter. In short there are two kinds of calling your events from your html, inline scripting and unobtrusive javascript. The latter has a variation called Event Delegation.

Inline scripting is the one we all know and the one that is not considered Best practice anymore. What you do is call the event from inside your html, like this:

<li onclick= "alert('foo');">inline script</li>

The disadvantages of this are multiple, one is maintenance, file size is another.

The correct way to do this, as all the cool kids know, is with unobtrusive javascript. That way you have smaller file size, easier maintenance and so on. So what you do in html is:

<li>foo</li>

And you set your events with the javascript on load, page ready or what not:

// go through the dom and attach a click on every li
jQuery('li').click(function(){
// do something when clicked.
alert('foo');
});

This is a step up, but it has a couple of disadvantages. As the number of event handlers grow, the time needed to add them increases. Not that this is a problem on any real browsers, but as long as IE6 continues to be used, you have to work with slow browsers. Enter Event Delegation.

With event delegation the amount of events you have to attach shrinks by a lot, as you can put them fairly high up, like on the body. So with identical html, in your javascript you do something like this:

// attach a click handler on the body (one)
jQuery('body').click(jQuery.delegate({
// when a li is the event target do stuff
'li': function() { alert('foo'); }
}));

This generates only one event handler, making it way faster another advantage of event delegation comes into play when you add elements to the dom, you don't need to attach the events again, as the handler is attached to a higher level.

So here is the deal, not only you get less code, you get even lesser code. Everybody wins!

Here are some links about event delegation should you be wanting to know more... (you can always ask me on twitter).

Here are the files I used for testing, first the inline scripting example, than the unobtrusive javascript one and last but not least the one with event delegation, have fun researching...

Technorati Tags:, , ,

on air tour (part 2)

Deploying and Updating AIR Applications (Serge Jespers)

Packaging, deploying and updating your application are probably the most important basics you'll need to know about. Serge will show you how to use Flex Builder 3 and the command line tools to sign and package your application, how to use the install badge, create custom install badges and how to keep your application up to date.

serge demostrates the world smallest video player, it plays hd in 16 by 16 pixels.

He then goes on with the presentation.

  1. step 1, get a certificate

    From thawte.com for 299 $ for one year with firefox. This to get a green (thrustworthy) icon in your installer.

  2. step 2 deploying your app

    using the standard install badge is one way.

    Another way is to use the beta install badge, looks nicer and has extra features. You can get it here

    The third way is to use a custom install badge, something you can build your self, so looks and functionality is up to you.

  3. step 3 Update your application

    He gives us 5 steps to do this, these I will hope to link to later, he will post them on his site. He explains how this is easy with flex in contrast with flash. As it already has a lot of stuff in it, to make development easier.

Adobe AIR API Overview (Daniel Dura)

Receive an overview of the new APIs that Adobe makes available to applications. Both and JavaScript examples will be shown.

Daniel Dura gives an overview of the most used api's, like window a subject you could spend a full day on covering it. He just covers the basics, normal window, lightweight window and utility window. Startmove() function is one of the reasons that I see myself writing air applications, it gives you so much extra functions...

After the html api, he goes to the File I/O api. This is the one that gives air so much extra over web applications. With this you have the possibility to read or write stuff to you computer. Make sure to close your filestream though, otherwise you will lock your computer..

Drag and drop / clipboard is another powerfull api to enhance the users experience. It enables the user to interact with your application in a normal manner, something that cost so much more trouble with just javascript.

For more info look at his site, which has the slides.

Data Intensive Enterprise AIR Applications (Enrique Duvos)

The need to optimize data handling and transfers in RIAs has become increasingly important in Enterprise applications. During this session Enrique will take a look at how the combination of Adobe AIR's offline local caches via SQLite, and its native connectivity to Adobe Livecycle Data Services data management services, gives developers a powerful framework to deliver data intensive RIAs outside the browser.

The first one which tell anything about preformance. Heard nothing about air's memory leak though. Explains the way that you can build flex and air apps with the same code base that talk to a java backend, very nice...

He shows a way to synchronize the data between client and server, in a nice way. You can check the connection and see if it's up or down, furthermore it can see if data is the same on or offline. Not sure if you have to use adobe's lifecycle though...

Maybe you can read about it on his site

Introduction to SQLite in Adobe AIR (Peter Elst)

Learn all about local database support with SQLite in Adobe AIR, how the use the available API's and build a complete data driven application from scratch. This session will help you get started with several tips and tricks on how to work with data in your desktop RIA's.

This is the one I hope to learn a lot from, if only pointers to where to start. It looks really easy, minimum amounts of code to do cool stuff. Paging is build in in a nice (not new) way, almost equal to mySql. Transactions look like a nice way to do lots of stuff in a fast and secure way.

I still don't know how the html is rendered in the air client, which is webkit and how it can or will affect performance... This will not be a problem with flex, which creates flash (imho).

Drag and drop is a part of flex/air that they are proud of showing, it is super easy and being shown now for the third time. Peter is using a trial version of flex builder, apparently all the money went to our lunch. Still this is by far the most interesting presentation so far, very good. The level is right for me, a bit over my head so I learn something but not too much.

He has a site, which has the slides on it.

on air tour (part 1)

this is a quick write up of the first part of the onair tour, I will clean this up later...

keynote Ryan stewart

Ryan Stewart, a Platform Evangelist at Adobe, provides an introduction to Adobe AIR and how it fits into the Adobe technology platform, and the larger RIA landscape.

marketing talk, adobe rules and stuff

focuses on the cross platform strength of air
talks about 'cocomo' and 'pacifica' server side stuff. nice, but still closed source...
air wants to bring the web developers to the desktop, by bringing the good parts of the web there.

shows a air app called uvlayer. Looks nice but still too much eye candy to me.
google analytics app is cool, adds animation in a nice unobtrusive way...
uses flash with html on one screen. pdf is used well, to render a print view.
mapcache is a cool app

why ria on the desktop?
branding, extended functionality. data access. you can use the flash player to access the same information on different platforms (web mobile desktop wii).

how
using existing tools like textmate or aptana.

new
1.1 more languages
post 1.1 three platforms the same...
max 2008 dec 1-4 2008 milan italy

Building your first Adobe AIR application with Adobe Flex (Mike Chambers)

Learn how to setup your development environment and build your first AIR application using Flex 3 and Flex Builder 3.

flexbuilder based on eclipse

configuration in xml looks easy.

flex looks nasty, absolute positioning and stuff

good warning on certification, get a good one if you go commercial

Building your first AIR application with HTML and JavaScript (Kevin Hoyt)

After this session you will know how to setup the Adobe AIR SDK to allow you to develop and package AIR applications from the command line. You will also be able to leverage the Adobe AIR command line tools to enable development of HTML and JavaScript based applications. Finally, the session will demonstrate built in support for AIR development from Adobe Dreamweaver and the Eclipse based Aptana.

shows how to build air apps with textmate and terminal. explains how app development is different than web development. app development has many things in common with java development

application sandbox? javascript is more insecure on the desktop, there is where the sandbox comes in. script injection and eval should be in the non-application sandbox and the application sandbox has the more advanced air js stuff.
html rules

Leveraging HTML and JavaScript within Adobe AIR (Kevin Hoyt)

Gain a better understanding of the HTML and JavaScript environments within Adobe AIR, and explore how these technologies can be leveraged in both Flash / Flex and HTML / JavaScript-based applications. JavaScript and ActionScript script bridging will be covered, as well as how to use AIR, Flash Player and ActionScript Library APIs directly from JavaScript.

even flex developers have the java bug, putting presentation in the structure, boe..
maybe it is for demo purposes, but the stupid thing is that tons of people will copy/paste this. so that is why it is important to build your demo's as clean as possible.

Kevin's site

A List Apart: new articles

With the introduction of a range of enhancements to form controls, APIs, multimedia, structure and semantics, HTML 5 promises to give authors more flexibility and greater interoperability.A preview of HTML 5

Flow, as a mental state, is characterized by a distorted sense of time, a lack of self-consciousness, and complete engagement in the task at hand. For designers, it’s exactly the feeling we hope to promote in the people who use our sites.A List Apart: Articles: Designing For Flow

Just browsing and found...

Nov 16, 2007 0 Comments
Tagged: , , , , and

I was just browsing and found these articles;

  1. A good article by Dave Shea about browser detection and other bad things here.
  2. Another article by Roger Johansson about the speed of browser vendors versus the w3c...
  3. Roel van gils talking about email obfuscation on alistapart
  4. PPK just updated his W3C dom compatiblity core tables
  5. a nice article over unobtrusive javascript
  6. An old article by Jonathan Snook about hosted subversion.
  7. Javascript keyboard madness by Jan Wolter.

As I will be attending @media ajax this year and I am buried in work, posting will be a little slow for the next few weeks, excuses for that.

Just browsing and found…

Nov 16, 2007 0 Comments
Tagged: , , , , and

I was just browsing and found these articles;

  1. A good article by Dave Shea about browser detection and other bad things here.
  2. Another article by Roger Johansson about the speed of browser vendors versus the w3c...
  3. Roel van gils talking about email obfuscation on alistapart
  4. PPK just updated his W3C dom compatiblity core tables
  5. a nice article over unobtrusive javascript
  6. An old article by Jonathan Snook about hosted subversion.
  7. Javascript keyboard madness by Jan Wolter.

As I will be attending @media ajax this year and I am buried in work, posting will be a little slow for the next few weeks, excuses for that.

Console.log for IE

I write a lot of javascript in my present project. Doing this, I just love firebug and more to the point the console.log function that it lets me use. Bummer is only that it doesn't work in IE, the one browser that needs javascript debugging most. It also throws javascript error in IE when used. That is something that can be avoided by cleanly remove all of those console.log statements before you send stuff to be tested.

But, as everybody knows in the real world people tend to forget such things. So in annoyance with these errors, I set out to recreate the basis console.log function for IE as well. In retrospect it turns out that I set out to create a better mouse trap, but hey, it was fun and good enough to share, so lets...

In my solution and do not worry, I will share other solutions but first I will speak my mind. The console.log function is not used, instead you use logger(message). This sends the message to message to the console, if there is any, or it creates an ul (with an id of 'logger') in which it sets li's with the individual messages. So without further ado, I present to you the code:

 /*
* wilfred nas
*
* info@wnas.nl
* http://www.wnas.nl/
* http://snippets.wnas.nl/
*/

// to intitialize the logger set : var log = 'true';
// change to 'false' to remove logging statements from you app.
// or (better) remove all logger statements from your code.
var log = 'true';
//var log = 'false';
/*
* the logger functionality is a attempt to recreate some of the console functions of
* fire bug for IE, the browser where you need js debugging tools the most. *
* to use it you replace console.log(msg) with logger(msg), this sends the msg to the console or
* it creates an ul to receive your (LIst of) messages...
*/
/*
* works in safari 2, opera 9, camino, webkit, ie 6 and firefox 2 (with or without firebug).
*/
function logger (msg){
if (log == 'true'){
// first we need to do some browser sniffing, look below for the explanation.
var b = navigator.userAgent.toLowerCase();
safari = /webkit/.test(b);
/*
we only sniff what we need...
opera = /opera/.test(b);
msie = /msie/.test(b) && !/opera/.test(b);
mozilla = /mozilla/.test(b) && !/(compatible|webkit)/.test(b);
*/
// bummer, safari seems to think that it has a console, so we make sure that it goes through.
if (window.console && !safari){
console.log(msg);
}
else {
if(!document.getElementById('logger')){
var ul = document.createElement('ul');
ul.id = 'logger';
document.getElementsByTagName('body')[0].appendChild(ul);
}
var ul = document.getElementById('logger');
var li = document.createElement('li');
ul.insertBefore(li,ul.firstChild);
li.innerHTML = msg;
}
}
}

I think that it is a nice solution to a real problem, if you want see my solution here. If you want to try other people's solutions, go and seek googles advice. Something that I should have done before writing my own stuff, but at least it helps me understand javascript a bit better. Something that is always good I think.

My advice to you is, either use my solution (and if you do, please let me know, I will be proud) or go and use faux console by Christian Heilman's. I think his is better javascript, as is to be expected...

The downside is that he wrote it to be included as a seperate piece of javascript and it still needs to have all of the console.log statements removed for the live code. Where as in my logger, all you have to do is change var log == 'true' to false to go live. I think that this is a strong point, in my situation where I deliver stuff to be tested in two day cycles, as it goes faster.

A time and a place for everything

In this day and age, personal publishing has taken off, you see this in the many people that maintain (or start) a blog, something that has been happening for a while now and the growth of which is over its top, they say. More different, or simular things are popping up now, things like twitter and tumblr.

As the possibilities grow, which will you choose, you can choose to take 'm all on, but to what purpose and in what time. I don't know about you, but for me there are just to few hours in a day. The time I spend online for me is not strictly for pleasure, but also for business purposes. So I try and do stuff as efficiently as possible.

Sure, I can choose to take on everything, but will I have something to tell about anymore, I don't think so. I blog about my work experience, talking about code and stuff, I use twitter to tweet about my daily ramblings and I plan to use my own tumblr as a digital clipboard.

But, what is the problem, a great many people do not know what to do with each medium, thus treating them all the same. How do we (including myself) tackle this problem, how do we maintain blogs that interest people, twitter streams that attract readers and a tumblr thingamagic that, ok I just started tumblr and should find out more about that before I give an stupid and unfounded opinion...

Not that that has stopped me in the past, or in the future for that matter, but hey, for the sake of this article, assume that I am a polite and thorough individual.

The point is, how do we make sense of the kaleidoscope of possibilities. What do we use to what purpose?

The answer is simple, use each tool where it is meant for and not for anything different. As a boy I used to help my dad doing chores, I didn't help out more than any other boy of about 6 (no more in fact than my boys do now), but I did learned an important lesson. Use a hammer to hammer and a screwdriver to screw. By doing this, you let the tool do what it does best and hinder you. I think that you can figure out what happens if you try to loosen a screw with a hammer. The same thing applies to things like blogs, twitter and tumblr. Best is to use each tool to do what they are good at...

So, what are the tools at hand good for? Lets analyse a few methods of sharing your mind on the web and discuss it's pro's and con's

Bloggin

pros

A blog is good for collecting and displaying thorough thought, even a link log is only a good one if it has vision. It needs a vision and a goal, not that those things should be heavy, but it seems hard to me to fill your blog with baby kittens and hardcore c++ snippets and not confuse people... So you have to select your goal and stick with it

cons

No good for jotting occasional ramblings, you have to keep at it, to satisfy your readers, you have to post regularly. And if you post, do not post something trivial. Respect the time of your reader as he or she is giving you by writing something worthwhile.

Twitter

Pros

Twitter is great as a shoutbox and it sometimes gives instant feedback. I like the insights it gives me in to the daily lives, that people are giving me, although it sometimes is a bit weird. To see total strangers share stuff about their lives. It sometimes makes me feel like a peeping tom, to see what people share about their lives. Some things are fun, but I can imagine that some things are better left unsaid.

Cons

I do not know what exactly to make of twitter as of now. What I know is that some people treat is like an anonymous shout-box. But anonymous it is not, it is an free online service that is available for anyone to read. And by anyone, I mean anyone, also your clients and (future) employers. So don't go overboard is my advice and think before you shout. Although that doesn't count for yelling IE is driving me mad once in a while if you are an web developer...

Tumblr

Pros

As I said above, I haven't been using it for a long time, and for now only use is to dump fragments of code to. The same thing that I started this blog for a couple of years back. With tumblr I feel no obligation to write thorough and thoughtful pieces, this frees me to just post useful pieces of code that won't make it into an article (yet). Therefor, I post more information online for people to see, read and use.

Cons

I think that the same policy should go for tumblr that you should use for twitter, use with caution. Tumblr on the other hand is more of a blog, in that you can edit your post, to possibly censure your self.

Conclusion

All of these tools have their own merits and can help you very well. If you use your twitter, you don't get tempted to shout on your weblog, tumblr can help you set up pieces to share and keep and not publish half finished articles. Each of these tools can enhance the other, they are so different that they do not get in each others way but enhance one another.

These sources that I talk about in this piece are not the only ones of their kind. So please, go look around the web for alternatives and try them out. As you do, you will be able to form your own solid opinion.

Please find your own way with these applications and use them wisely. My opinion of these is not the only, so I advise you to form your own opinion on them.

Technorati Tags:, , ,

@media Ajax

Sep 15, 2007 0 Comments
Tagged: , and

PPK has gotten me interested in this and it is looking better everytime more info is getting available. Maybe I will go, two @media's a year is better than one, don't you think?@media Ajax

UpdateI am going, just booked. Pretty exciting, this is my first time going to a major conference as a independent contractor. That means, booking flights, hotels and stuff. If any other dutch people are going, please let me know... Happy clog or front end gilde meeting in london, I'm in...