Sunday, December 12, 2010

Native Apps vs Web Apps

The Issues Native Apps Web Apps
Internet access Not required Required, except for rare apps with offline capability
Installation/updates Must be deployed or downloaded Hit refresh
User interface Native apps are responsive and functional Browsers can be clunky, but new advancements in JavaScript like jQuery Mobile are catching up fast
Device compatibility Platform-dependent, hardware-dependent Platform-agnostic, content can be reformatted with CSS to suit any device
Animation/Graphics Fast and responsive Web apps are getting closer, but will probably always lag
Streaming media Few problems with audio and video. Flash works, but only if the device supports it Flash works where supported. Browser-based audio and video are getting there, but still beset by compatibility headaches. Give it a year or two
Fonts Tight control over typefaces, layout Almost on par, thanks to advancements in web standards. Give it six months
Is my content searchable? Not on the web By default
Sharable/Tweetable? Only if you build it in Web links are shared freely. Social APIs and widgets allow easy one-click posting
Discussion and collaboration Only if you build it, and it’s more difficult if data is disparate Discussion is easy, all data is stored on a server
Access to hardware sensors Yes, all of them: camera, gyroscope, microphone, compass, accelerometer, GPS Access through the browser is limited, though geolocation is common
Development Specific tools required for some platforms (like Apple’s). You have to build a new app for each target platform Write once, publish once, view it anywhere. Multiple tools and libraries to choose from
Can I sell it? Charge whatever you want. Most app distributors take a slice, up to 30% Advertising is tolerated, subscriptions and paywalls less so. No distribution costs beyond server fees
Distribution Most app stores require approval. And you gotta wait No such hassle
Outside access to your content No, the reader must download your app Yep, just click a link
Advertising Control over design (though limited in iAds) and rate More choices for design, plus access to web analytics. Rates vary widely

Thursday, December 9, 2010

Frameworks for developing mobile web apps

Smart Phones are the future of the next gen web. There’s a lot of buzz with the new mobile web frameworks and mobile platforms. There’s also a lot of confusion and vague terms being thrown around that are causing people to misunderstand what each of these tools do.I did a small research to understand some of them and to clear doubts i had.

Types of Mobile Apps :
  • Native Apps - written using Android SDK Java(for android phones) , Cocoa Objective-C (for IOS/IPhone).
  • Web Apps - written using Sencha Touch or JQuery Mobile frameworks (in normal web technologies Js/Html/css)
  • Web Apps which look like Native Apps - wrapped using Titanium or Phonegap frameworks which can access some of the mobile devices native APIs using javascript
We have many frameworks for developing native and web apps. Interestingly , we have some more frameworks for converting(wrapping) webapps to native apps.These wrapper frameworks provide some Javascript native APIs through which a "web app" has access to the mobile phone functions such as Geolocation, Accelerometer Camera, Contacts, Database, File system, etc .

Developing Native apps and Web apps in mobiles have their pros and cons. Lets discuss about each of the type below :

Native Apps

A native app is defined as the software specifically written to run on a device’s operating system and machine hardware, and typically needs to be rewritten for different devices.A native app runs on your device.All of it’s resources are installed locally on your machine.A native app uses platform and language specific API’s native to that device.A native app has access to local resources while a mobile web app cannot.

We have to write a native app in Java Android sdk for android based devices and upload them to android app market. If we need to make that app for Iphone , then we need to write the same in Objective-c(cocoa) to run it in IOS and upload it to apple appstore.The same applies for symbian, blackberry and other OS s too. Unless you are a Backend(Java/Obj-c) developer , you wont be much interested in this.

Web apps

The future of the Mobile Web is likely to be dominated by cross-platform browser-based mobile web sites - rather than apps built specifically for iPhone, Android, or any other platform.
A mobile web app is not the same as a mobile native app. A mobile web app runs in your browser.Think of a mobile web app as a website like facebook.com or Twitter.com. Almost all of the app’s resources are remote, stored on some server somewhere. Sure there might be some local storage happening but at the end of the day it’s a website application. Check out for more differences here.

A Web app is typically coded in a browser-rendered language such as HTML,CSS combined with JavaScript. Direct control over the application’s distribution and cost advantages are usually the main reasons for launching a Web application. For webdevelopers,its very easy to build them and requires no app store approval.
Frameworks like Sencha Touch and JQuery Mobile can give native look for the webapps.The difference between the capabilities of Web-based and native mobile apps is narrowing rapidly with the invent of these frameworks.

Sencha Touch and jQuery Mobile

These are mobile web frameworks. You can use these technologies to create web-based mobile apps. Both of these projects run in javascript.

Sencha Touch, the first HTML5 mobile JavaScript framework that allows you to develop mobile web apps that look and feel native on iPhone and Android touchscreen devices. Sencha Touch is a cross-platform library aimed at next generation, touch-enabled, devices. With Sencha Touch you write an object-oriented javascript application that generates HTML markup.Higher learning curve than most other web frameworks but best one for writing high level web applications.

JQuery Mobile (1.0 Alpha 2) is built on the famous JQuery requires JQuery 1.4.4. JQuery Mobile uses the very best HTML 5 and CSS 3 features to provide the best possible experience in the most-capable browsers.JQuery Mobile aims to be more mature and as much cross browser as possible.The following quote describes best of it.

“A unified user interface system across all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation. Its lightweight code is built with progressive enhancement, and has a flexible, easily themeable design.”

JQuery Mobile (like jQuery )adds interactivity and styling to ‘classic’ declarative HTML, probably generated on the mobile site’s server side.

Sencha Touch (like ExtJS) is more of a programmatic approach, where a mobile app is written almost entirely in Javascript, and creates the majority of the HTML itself on the client when executed.

Sencha Touch seems very sophisticated and use it if we had to build a complex feature rich web app. But Jquery mobile supports more devices & platforms and has less learning curve.In future it might include many rich features.So i support JQuery.

PhoneGap and Titanium


Titanium is a cross platform technology that goes beyond the mobile and currently supports iPhone, Android devices, desktop applications, Windows and Mac, with plans to support the BlackBerry in the near future.The idea behind the Titanium platform is that you write your applications with web technologies like javascript APIs and html, and when you want to test your application, Titanium will compile your code in a native application. Which mean that you can in fact write one application for the iPhone and Android in titanium and the framework will compile it for those platform separately.

Titanium doesn’t compile HTML and JavaScript into native applications (as some people might think) but instead acts as a JS API that links to pre-compiled native objects. What’s the difference? Well a Titanium app will not have the performance of a fully native app nor does it give you full access to the all native API elements.

PhoneGap serves as a wrapper for the browser. PhoneGap opens a webkit view in a native application. So your html and css is shown exactly how it will look in the real application. Titanium can do the exact same thing via “webViews” but Titanium takes it a step further by offering a slew of native APIs for Cocoa/Android Touch outside the browser.

PhoneGap and Titanium are not similar to Sencha Touch and jQuery Mobile.Both allow you to distribute native or native-like apps. A lot of people think that Titanium and PhoneGap are in competition with Sencha Touch and jQuery Mobile. But its wrong , they are used as wrappers.
Both don’t need to “build support” for Sencha Touch or jQuery Mobile. Why? Because the devices they support come with browsers. Remember, Sencha Touch and jQuery Mobile run in the browser. Since both PhoneGap and Titanium allow you to run things in a given device’s browser, they already have support for Sencha Touch and jQuery Mobile.

You can use Sencha Touch and jQuery Mobile inside both PhoneGap and Titanium. If you decide your html/js to be cool as a native app, you can use either PhoneGap or Titanium to wrap a browser around your app and put it in the app store or marketplace. This is where the confusion comes. Putting your Sencha Touch or jQuery Mobile apps in a native wrapper doesn’t make it a native app. It makes it appear as if it is a native app. You might get some extra functionality from PhoneGap or Titanium API’s, but it’s still not necessarily a ‘native’ app. It’s a web app running locally on the device. It’s a great way to use web technologies inside a native-like area.


Friday, November 12, 2010

Duplicate IDs in HTML

IDs should be unique according to the standards and whilst most browsers don't show errors when handed duplicate IDs it would not be a good idea to rely on that always being the case.

Making the ID unique by adding a type name to the ID would work but you need to ask why you need it. Giving an element an id is very useful when the element needs to be found, getElementById is very fast. The reason its fast it that most browsers will build an index of IDs as its loads the DOM. However if you have zillions of IDs that you never actually need to use in something like getElementById then you've incurred a cost that is never paid back.

So Conclusion is even browsers allow us to use duplicate IDs ,its not a good practice to use. And getElementById() should also give appropriate result , so better to avoid it.

Thursday, May 20, 2010

The Mysterious JavaScript 'This' Keyword.

The this keyword

One of the most powerful JavaScript keywords is this. Unfortunately it is hard to use if you don't exactly know how it works.

Below I explain how to use it in event handling.
Later on I'll add some information about other uses of this.

Owner

The question that we'll discuss for the remainder of the page
is: What does this refer to in the function doSomething()?

function doSomething() {
this.style.color = '#cc0000';
}

In JavaScript this always refers to the “owner” of the function
we're executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its owner
is the page, or rather, the window object (or global object) of JavaScript. An onclick
property, though, is owned by the HTML element it belongs to.

This "ownership" is the result of JavaScript's object oriented approach.
See the Objects as associative arrays page for some more information.


------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          --------------------                          |
|          | onclick property |                          |
|          --------------------                          |
|                                                        |
----------------------------------------------------------

If we execute doSomething() without any more preparation the this
keyword refers to the window and the function tries to change the style.color of the window. Since the
window doesn't have a style object the function fails miserably and produces JavaScript errors.

Copying

So if we want to use this to its full extent we have to take care that the function that uses it
is "owned" by the correct HTML element. In other words, we have to
copy the function to our onclick property.
Traditional event registration takes care of it.

element.onclick = doSomething;

The function is copied in its entirety to the onclick property (which now becomes
a method). So if the event handler is executed this refers to the HTML element and its
color is changed.

------------ window --------------------------------------
|                                                        |
|                                                        |
|                                                        |
|   ----------------                                     |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------                       |
|                                                        |
----------------------------------------------------------

The trick is of course that we can copy the function to several event handlers. Each time this
will refer to the correct HTML element:

------------ window --------------------------------------
|                                                        |
|                                                        |
|                                                        |
|   ----------------                                     |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------          |            |
|                                           |            |
|   -----------------------                 |            |
|   | another HTML element| <-- this        |            |
|   -----------------------     |           |            |
|               |               |           |            |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------                       |
|                                                        |
----------------------------------------------------------

Thus you use this to the fullest extent. Each time the function is called,
this refers to the HTML element that is currently handling the event, the HTML
element that "owns" the copy of doSomething().

Referring

However, if you use
inline event registration

<element onclick="doSomething()">

you do not copy the function! Instead, you refer to it, and the difference is crucial.
The onclick property does not contain the actual function, but
merely a function call:

doSomething();

So it says “Go to doSomething() and execute it.” When
we arrive at doSomething() the this keyword once again refers to the global
window object and the function returns error messages.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------         / \           |
|          | go to doSomething() |          |            |
|          | and execute it      | ---- reference to     |
|          -----------------------       function        |
|                                                        |
----------------------------------------------------------

The difference

If you want to use this for accessing the HTML element that is handling the event,
you must make sure that the this keyword is actually written into the onclick property.
Only in that case does it refer to the HTML element the event handler is registered
to. So if you do

element.onclick = doSomething;
alert(element.onclick)

you get

function doSomething()
{
this.style.color = '#cc0000';
}

As you can see, the this keyword is present in the onclick method.
Therefore it refers to the HTML element.

But if you do

<element onclick="doSomething()">
alert(element.onclick)

you get

function onclick()
{
doSomething()
}

This is merely a reference to function doSomething(). The this
keyword is not present in the onclick method so it doesn't refer to the HTML element.

Examples - copying

this is written into the onclick method in the following cases:

element.onclick = doSomething
element.addEventListener('click',doSomething,false)
element.onclick = function () {this.style.color = '#cc0000';}
<element onclick="this.style.color = '#cc0000';">

Examples - referring

In the following cases this refers to the window:

element.onclick = function () {doSomething()}
element.attachEvent('onclick',doSomething)
<element onclick="doSomething()">

Note the presence of attachEvent(). The main drawback of the
Microsoft event registration model
is that attachEvent() creates a reference to the function and
does not copy it. Therefore it is sometimes impossible to know which HTML currently handles the event.

Combination

When using inline event registration you can also send this to the function
so that you can still use it:

<element onclick="doSomething(this)">
function doSomething(obj) {
// this is present in the event handler and is sent to the function
// obj now refers to the HTML element, so we can do
obj.style.color = '#cc0000';
}

JavaScript Apply() and Call() Methods

JavaScript 1.3 includes two new methods for the Function object, call() and apply(). The apply() method is a variation on the call() method. The apply() method lets you pass the parameters from one method to the other in a different way than the call() method does it. The call() method requires the full list of parameters.

The apply method allows you to call a function and specify what the keyword this will refer to within the context of that function. The thisArg argument should be an object. Within the context of the function being called, this will refer to thisArg. The second argument to the apply method is an array. The elements of this array will be passed as the arguments to the function being called. The argArray parameter can be either an array literal or the deprecated arguments property of a function.

The apply method can be used to simulate object inheritance as in the following example. We first define the constructor for an object called Car which has three properties. Then the constructor for a second object called RentalCar is defined. RentalCar will inherit the properties of Car and add one additional property of its own - carNo. The RentalCar constructor uses the apply method to call the Car constructor, passing itself as thisArg. Therefore, inside the Car function, the keyword this actually refers to the RentalCar object being constructed, and not a new Car object. By this means,the RentalCar object inherits the properties from the Car object.

Code:
function Car(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
}

function RentalCar(carNo, make, model, year)
{
this.carNo = carNo;
Car.apply(this, new Array(make, model, year))
}

myCar = new RentalCar(2134,"Ford","Mustang",1998)
document.write("Your car is a " + myCar.year + " " +
myCar.make + " " + myCar.model + ".")

Output:
Your car is a 1998 Ford Mustang.

NOTE: The apply method is very similar to the call method and only differs in that, up until now, you could use the deprecated arguments array as one of its parameters.

Wednesday, May 19, 2010

IE9 Browser

Can IE9 rule the world and end the saga of Mozilla? Will it make Microsoft to dominate in the internet world?

http://news.cnet.com/8301-30685_3-20000433-264.html?tag=mncol

Thursday, May 13, 2010

HTML5 & CSS3 Readiness.

The below site gives info about all the HTML5 features and where the browsers stand in implementing each of them. Just click the below link and hover over each ray.

http://html5readiness.com/





HTML5 & CSS3 Readiness [html5readiness.com] is a relatively simple but cute data dashboard, completely created with CSS3, which tracks how much support exists for each new HTML/CSS feature.

The different browsers are grouped into color schemes based on their underlying rendering engine: all Firefox versions are shades of blue, Chrome/Safari - yellow, IE - pink. Each ray also has a different background color if it is a CSS3 feature. Each browser is represented with a tile on the bar and with an equal width of space. As a result, if a single bar is full, that specific feature has universal support among all the 8 browsers.

Tuesday, May 11, 2010

Show/Hide Performance Using JQuery

The "High Performance JQuery" presentation especially caught my attention when the speaker, Robert Duffy, said that .hide() and .show() were slower than changing the css directly.I benchmarked the various ways to hide DOM elements and looked into the jQuery source to find out what is going on.

The HTML I tested against was a page of 100 div tags with a class and some content, I cached the selector $('div') to use with each method to exclude the time needed to find all the div elements on the page from the test. I used jQuery 1.4.2 for the testing, but keep in mind that the algorithms behind the method calls can change dramatically from version to version. What is true for 1.4.2 is not necessarily true for other versions of the library.

The methods I tested were .toggle(), .show() & .hide(), .css({'display':'none'}) & .css({'display':'block'}), and .addClass('hide') & .removeClass('hide'). I also tested modifying an attribute of a <style> element.

.show() & .hide()

These were, in fact, comparatively slow methods of hiding DOM elements across all browsers. One of the main reasons is that .hide() has to save the notion of what the display attribute was before, so that .show() can restore it. It does this using the .data() jQuery method, storing that information on the DOM element. In order to do so, .hide() loops through every element twice: once to save the current display value, and then once to update the display style to none. According to a comment in the source, this prevents the browser from reflowing with every loop. The .hide() method also checks to see if you pass in a parameter to animate the hiding with an effect. Even passing in a 0 dramatically slows down the performance. Performance was slowest on the first call to .hide(); subsequent calls were faster.

Browser      hide/show
FF3.6 -         29ms / 10ms 
Safari 4.05 -   6ms / 1ms
Opera 10.10 -   9ms / 1ms
Chrome 5.0.3 -  5ms / 1ms
IE 6.0  -       31ms / 16ms 
IE 7.0  -       15ms / 16ms 

.toggle()

This was, by far, the slowest method of hiding all of the div elements. It iterates through every element returned by the selector, checks to see if the element is currently visible, and then calls .hide() on visible elements one at a time and .show() on hidden ones one at a time. It also has to check to see if you are passing in a boolean to force everything to .show() or .hide() and check to see if you are passing in functions to toggle instead of toggling visibility. There seems to be some opportunity for optimization of this function, as one could select all of the hidden elements of the selector and call .show() on them all at once and then select the remaining elements in the selector and call .hide() on them at the same time. If you are so inclined, I encourage you to check out the source and see if you can eke out any performance gains.

Browser      hide/show
FF3.6 -         80ms / 59ms 
Safari 4.05 -   24ms / 30ms 
Opera 10.10 -   67ms / 201ms
Chrome 5.0.3 -  55ms / 20ms 
IE 6.0  -       296ms / 78ms 
IE 7.0  -       328ms / 47ms 

.addClass() & .removeClass()

These are pretty snappy methods of hiding/showing elements of the DOM, twice as fast as .show() & .hide() in Firefox and three times as fast in Safari. The differences in IE 6, IE7, Chrome, and Opera are negligible. It's also worth noting that with 100 DOM nodes, we're talking a total difference of 18ms in Firefox and 4ms in Safari. The speed difference will only be relevant for very large selections. Adding and removing a class requires a bit more management on your part, since you have to create the class that has a display of none and then have to keep track of CSS priority to make sure your elements get hidden. The way jQuery adds and removes a class is through string manipulation, so I imagine that as the number of classes on an element grows, this method will get slower, but that is untested speculation on my part.

Browser      hide/show
FF3.6   -       11ms / 11ms 
Safari 4.05 -   2ms / 2ms
Opera 10.10 -   6ms / 3ms
Chrome 5.0.3 -  3ms / 1ms
IE 6.0  -       47ms / 32ms
IE 7.0  -       15ms / 16ms

.css({'display':'none'}) & .css({'display':'block'});

These methods were very snappy. They showed an improvement over .addClass() and .removeClass() in Opera and IE 6/7 and about the same in other browsers. They work great if you know the current display style of all the elements you are changing, or at least have not changed the display style inline. If you have changed the display style inline, then you will need to make sure you set the correct value when you make the element visible again. If you are just using the elements' default display value or set the display value in the css, then you can just remove the style like so, .css({'display':''}), and it will revert to whatever value it has in the css or by default. As a library, jQuery can't assume that the display element wasn't set inline, so it has to manually keep track of it. That is the main slowness you can avoid since you know you won't be setting the display inline.

Browser      hide/show
FF3.6   -       14ms / 12ms
Safari 4.05 -   2ms / 1ms
Opera 10.10 -   2ms / 2ms
Chrome 5.0.3 -  2ms / 1ms
IE 6.0  -       16ms / 16ms
IE 7.0  -       0ms / 0ms  // The usual caveat about inaccuracy of IE clocks applies.

Disabling stylesheets

For fun, I thought, "What if instead of manipulating every DOM node and changing things, we just futz with the stylesheet?" Could there be speed improvements there? I mean, the methods benchmarked above are plenty fast for everyday use, but what if I had 10,000 nodes on a page I wanted to show and hide? It would be slow just selecting them all. But, if I could manipulate the stylesheet, I could avoid the entire overhead. Let me just tell you that way is fraught with peril.

There are, of course, cross browser issues when manipulating stylesheets, since jQuery doesn't abstract them away for you. First, I tried to see if I could append a style tag with the css class as a string using jQuery, but got inconsistent results across browsers. Then I tried creating the stylesheet node and class using JavaScript, but there were different APIs and it ended up being too slow to justify. So finally, forgoing an attempt to do this in a programmatic way, I ended up just writing a style tag with a class in the head of the document. It's far too slow to create the stylesheet programmatically, but if it's already there then it is trivial to give it an ID and use its disabled attribute.

HTML:
  1. <style id="special_hide">.special_hide { display: none; }</style>
  2. <!--  ...  -->
  3. <div class="special_hide">Special hide DIV</div>

Then in javascript…

JavaScript:
  1. $('#special_hide').attr('disabled, 'true');

and BAM, you just displayed all of your elements with a class of “special_hide”. To hide them all again, just do…

JavaScript:
  1. $('#special_hide').attr('disabled', 'false');

and they are now all hidden. The total javascript processing time was 0-1ms across all browsers. The only javascript you are doing is changing an attribute. Of course, there is still the time the browser takes to reflow and repaint the page, but you've virtually eliminated all the javascript processing time. If you call any of the other methods, .toggle(), .hide(), or .css(), this method will stop working on those elements because they set the css style inline, which has higher precedence than other css. To make this method work again, simply do a .css(‘display’, ‘’) to remove the inline style. This method also requires the most work on your part, because you have to define the class and give the class to all of the elements on the page you want to show/hide at the same time, but if you are dealing with extremely large sets, this might just be worth it.

To recap, here is a list of methods to change the display of elements in order from fastest to slowest:

  1. Enabling/Disabling a stylesheet
  2. .css('display', ''), .css('display', 'none')
  3. .addClass(), .removeClass()
  4. .show(), .hide()
  5. .toggle()

Also note that for the majority of use cases, all of these methods are plenty fast to use. When you start having to manipulate large jQuery collections, .show() and .hide() might become too slow in IE, and you might need to bump up to .addClass() or .removeClass(). Enabling/disabling of stylesheets would only be necessary in the most extreme cases, but if things are hiding to slowly for you, you might want to give it a try.

Courtesy : Josh Powell

Friday, April 30, 2010

Monday, April 19, 2010

CSS3 - Practical Uses

One big item for me is how much we use CSS3. Yes I know, it is not fully supported across all browsers. If you still want everything to look exactly the same across all browsers, you should probably just close this article and not read about CSS for another 10 years. A user is not going to pull up your site in two different browsers to compare the experience, so they won't even know what they are missing. Just because something is not fully supported, that does not mean that we can't use it to an extent. In this article I'll show you some practical uses for CSS3.


Border Radius

This is probably the most used CSS3 property. If you want rounded corners, and they aren't essential to your design (which they rarely should be), then this is the way to go. If a user's browser doesn't support it, then you get square corners, no big deal.

One simple use of border radius is for form elements. Here is an example of your standard text input with a button with some simple styling:

  

Definitely nothing special and some people may not even realize that the submit button is actually a button. Sure, you could swap it out with an image, but that solution can be a pain if you have a site with a lot of different buttons. So let's just add a little CSS3 and make the input and button a little more attractive.

  

The Code

Who would have thought simple rounded corners make the form so much more appealing?

.radius {
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

So this code is just saying to give each corner a 3px radius. Just like properties like margin and padding, you can pass in multiple values to account for each corner.

Example

.radius2 {
 border-radius: 3px 6px 8px 10px;
 -moz-border-radius: 3px 6px 8px 10px;
 -webkit-border-radius: 3px 6px 8px 10px;
}

  

It is unfortunate that we have to add the -moz-border-radius and -webkit-border-radius properties, but like a lot of the other CSS3 properties, browser makers are adding proprietary properties until the official properties are finalized.

One really confusing thing to note here is that the syntax for rounding a single corner is different for Firefox than the W3c spec:

  • border-top-left-radius
    -moz-border-radius-topleft / -webkit-border-top-left-radius
  • border-top-right-radius
    -moz-border-radius-topright / -webkit-border-top-right-radius
  • border-bottom-right-radius
    -moz-border-radius-bottomright / -webkit-border-bottom-right-radius
  • border-bottom-left-radius
    -moz-border-radius-bottomleft / -webkit-border-bottom-left-radius

RGBa

Using an RGBa color value is the same as using an RGB color, except that you can pass in a value to specify the amount of transparency (the "a" in RGBa stands for alpha).

RGBa is awesome because unlike opacity, only the background is given transparency. You can get a nice effect by applying RGBa to a caption overlayed on top of a photo.

The Code

The code necessary to use RGBa is very simple:

.caption { background: rgba(255, 255, 255, .5); }

But, if you are using a browser that does not support RGBa, there will be no background color at all. So, you should specify a normal background color first:

.caption { 
 background: rgb(235, 243, 240);
 background: rgba(255, 255, 255, .5); 
}

Example

"The Nature" - EARTH

Just so you can see the difference between RGBa and opacity, let's use the same example but use opacity instead of RGBa.

"The Nature" - EARTH

It may be a little hard to notice, but the actual text in this example is semi-transparent as well.

.caption {
 background: #fff;
 filter: alpha(opacity = 30);
 opacity: 0.3;
}

Multiple Background Images

How many times have you had to nest multiple elements just because you couldn't add multiple background images to a single element? I can't even count the number of times. So let's pretend that you wanted to create a box like the following image, but it could have varying amounts of height.

Example of box to be created with multiple background images

To create a box like this, you would need to split our larger image into the following pieces:

Top:

Top image for multiple backgrounds

Bottom:
Bottom image for multiple backgrounds

Repeating Background:
Repeating background for multiple backgrounds

Since we have multiple images, we would need three elements to attach them to. So that stinks, we are adding extra elements just for presentational purpose. This is a perfect example where we can utilize multiple backgrounds on a single element, and if a browser didn't support it, then it would just get a solid background color.

The Code

Here is the code we would need to attach multiple background images to a single element:

.multi-bg {
 background: url(/image/css3-multi-top.png) no-repeat,
 url(/image/css3-multi-bottom.png) no-repeat 0 100%,
 url(/image/css3-multi-repeat.png) repeat-y;
 background-color: #516ac4;
}

The images are layered onto the element with the first image being the top-most image. You add the images in a comma separated list, and I would recommend setting the background-color as another property so that browsers that don't support multiple background images at least get the solid color.

Example

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae risus ac nisl imperdiet semper. Duis egestas odio in ipsum varius consequat. Nunc in erat libero, nec interdum tortor! Aliquam facilisis hendrerit consequat? Praesent a risus in augue tincidunt cursus! Cras facilisis leo in lectus malesuada ut eleifend lacus viverra. Nulla purus nunc, bibendum nec lobortis ut, luctus sed massa? Nulla facilisi. In in mi odio, eu blandit est. In hac habitasse platea dictumst. Sed pulvinar condimentum purus et aliquet. Nam non ipsum quis metus luctus varius. Nullam placerat congue tincidunt!

Note: Mozilla browsers don't even support this property yet, check it out in a Webkit browser.

Box Shadow

Drop shadows are such a pain to add to elements, especially when there can be a varying amount of height or width. Adding drop shadows is now as easy as adding a few lines of code, instead of messing around with multiple images and multiple elements.

The Code

.box-shadow {
 box-shadow: 6px 6px 4px #cecece;
 -moz-box-shadow: 6px 6px 4px #cecece;
 -webkit-box-shadow: 6px 6px 4px #cecece;
}

The first value is the horizonal offset, and the second is the vertical offset. The third vaue is the blur radius. The higher the number, the less sharp and larger the shadow becomes. The final value is the color of the shadow. Note: RGBa colors are allowed too.

Example

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae risus ac nisl imperdiet semper. Duis egestas odio in ipsum varius consequat. Nunc in erat libero, nec interdum tortor! Aliquam facilisis hendrerit consequat? Praesent a risus in augue tincidunt cursus! Cras facilisis leo in lectus malesuada ut eleifend lacus viverra. Nulla purus nunc, bibendum nec lobortis ut, luctus sed massa? Nulla facilisi. In in mi odio, eu blandit est. In hac habitasse platea dictumst. Sed pulvinar condimentum purus et aliquet. Nam non ipsum quis metus luctus varius. Nullam placerat congue tincidunt!

If a browser does not support box shadow, then there is just no drop shadow. No big deal in my opinion.

Text Shadow

Text shadow is actually a CSS2 property, but it's finally starting to be supported, so that's why I'm mentioning it. It has the exact same syntax as box shadow, and if a browser doesn't support it, then you get no shadow.

The Code

.text-shadow {
 text-shadow: 1px 2px 3px #1a1a1a;
}

Example

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae risus ac nisl imperdiet semper.

Multi Column Layout

I actually don't think multi column layout is that useful, except for shorter columns of text, but it is pretty cool.

The Code

.columns {
 -moz-column-count: 3;
 -moz-column-gap: 1em;
 -moz-column-rule: 1px solid black;
 -moz-column-width: 200px;
 -webkit-column-count: 3;
 -webkit-column-gap: 1em;
 -webkit-column-rule: 1px solid black;
 -webkit-column-width: 200px;
}

You actually wouldn't use all of these properties together, but these are the supported properties for multiple colummn layout. As of right now, these properties are only supported by Mozilla and Webkit browsers, so the -moz and -webkit prefixes are needed. If a user is not using a Mozilla or Webkit browser, they would just see a single column of text.

The column count property takes an integer value that specifies the number of columns. The column gap specifies the width of the gap that should be between the columns. The column rule describes the rule between the columns, and the format of this property is just like the border property. The column width property accepts a width as a value that describes how wide each column should be. Typically you would use column count or column width to set the number of columns.

Example

In this example, we will use column count instead of column width:

.columns {
 -moz-column-count: 3;
 -moz-column-gap: 20px;
 -moz-column-rule: 1px dotted #666;
 -webkit-column-count: 3;
 -webkit-column-gap: 20px;
 -webkit-column-rule: 1px dotted #666;
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae risus ac nisl imperdiet semper. Duis egestas odio in ipsum varius consequat. Nunc in erat libero, nec interdum tortor! Aliquam facilisis hendrerit consequat? Praesent a risus in augue tincidunt cursus! Cras facilisis leo in lectus malesuada ut eleifend lacus viverra. Nulla purus nunc, bibendum nec lobortis ut, luctus sed massa? Nulla facilisi. In in mi odio, eu blandit est. In hac habitasse platea dictumst. Sed pulvinar condimentum purus et aliquet. Nam non ipsum quis metus luctus varius. Nullam placerat congue tincidunt!

The reason that I think this type of layout is only good for shorter passages of text is because if the columns were taller than the height of the viewport, I don't think it would be a great user experience.

Border Image

This was honestly one of the most confusing properties that I had ever read about. But once you take your time to understand it, it's very useful.

The Code

.border-img {
 background-color: #516ac4;
 border: 10px solid;
 border-image: url(/image/css3-border-img.png) 10 10 10 10 repeat repeat;
 -moz-border-image: url(/image/css3-border-img.png) 10 10 10 10 repeat repeat;
 -webkit-border-image: url(/image/css3-border-img.png) 10 10 10 10 repeat repeat;
}

We are going to recreate the same example that we used for the multiple background images, using a single image. Here is the image we will use:

Image used for border image property

The value specified in the border property is how wide we want our image to be bordered around the element. The first value in the border-image property is the actual image we are using for the border, and the next four values are setting up the coordinates so it knows which piece of the image to use where. Just like many other CSS properties, the first coordinate is the top value and works its way around clockwise. The final values in the property tells the code to repeat the portion of the image on all sides to fill in the gaps.

In the next image, you can see our small image, enlarged, and with guides setup to match the coordinates in the CSS.

Enlarged version of border image

Example

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae risus ac nisl imperdiet semper. Duis egestas odio in ipsum varius consequat. Nunc in erat libero, nec interdum tortor! Aliquam facilisis hendrerit consequat? Praesent a risus in augue tincidunt cursus! Cras facilisis leo in lectus malesuada ut eleifend lacus viverra. Nulla purus nunc, bibendum nec lobortis ut, luctus sed massa? Nulla facilisi. In in mi odio, eu blandit est. In hac habitasse platea dictumst. Sed pulvinar condimentum purus et aliquet. Nam non ipsum quis metus luctus varius. Nullam placerat congue tincidunt!

It's pretty cool that we can create this box with just one tiny image, thus reducing our number of HTTP requests.

Conclusion

These are just a few examples of practical uses of the new features in CSS3 that I think you can start using today. I'm sure there are many other examples, so get in the holiday spirit and share in the comments.


Courtesy by : Trevor Davis

Saturday, April 10, 2010

JQuery Custom Selectors

To the wide variety of CSS and XPath selectors, jQuery adds its own custom selectors. Most of the custom selectors allow us to pick certain elements out of a line-up, so to speak. The syntax is the same as the CSS pseudo-class syntax, where the selector starts with a colon (:). For example, if we wanted to select the second item from a matched set of divs with a class of horizontal, we would write it like this:


$('div.horizontal:eq(1)')

Note that the eq(1) gets the second item from the set because JavaScript array numbering is zero-based, meaning that it starts with 0. In contrast, CSS is one-based, so a CSS selector such as $('div:nth-child(1)') gets any div that is the first child of its parent.

Convert jQuery object to DOM object

jQuery object is a wrap of the DOM object, but itself is not a DOM object. If you want to get the DOM object from the jQuery object, you should use get() method.

For example, if the jQuery object includes only one DOM object, you can use

$("div").get(0)

or

$("div")[0]

However, if you have multiple DOM objects, you can use

$("div").get()

JQuery's This

More often that not, in my early dabbling with jQuery and more advanced JavaScript, I found I would constantly get confused over the meaning of "this" in jQuery and my own new libraries.

Hopefully this quick guide can help clarify those confusing moments, because once you've got it, it's simple as pie.

What is "this"?

In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.

There are really two main contexts of 'this' in jQuery. The first refers to a to a DOM element, and the second to a jQuery object.


Object Methods vs Instance Methods
Object Methods/Global Methods : JQuery.objMethod = function () { ...... } (or)
$.objMethod = function () { ...... }
// We cant use this method on any elements(jquery selectors)and so the 'this' keyword.

Instance Method : JQuery.fn.insMethod = function () { ........ }
// We can use this method on elements(jquery selectors) and so the 'this' keyword.

Source: http://en.wikipedia.org/wiki/This_(computer_science)

JQuery's this

Example of this as a DOM element

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

The following code searches for anchor links with the class of 'newTarget' and sets the 'target' attribute to '_new' (which is a trick to create strict XHTML while still having some links open in a new window).

In this example we are also going to perform a double check to ensure links to the same domain don't open in a new window using the this object.

$('a.newTarget').each(function() { // <- our anonymous callback
  // check the DOM attribute 'host' on this
  if (this.host != window.location.host) {
    // create a jQuery object using the current DOM element
    $(this).attr('target', '_new');
  }
});

Example of this as a jQuery object

'this' is a jQuery object when you are inside your own jQuery functions. Note that the result of a selector query (i.e. $('a') ) is a jQuery object, which is an array of the matched DOM elements (imagine jQuery is an array with bells on).

jQuery.fn.newTarget = function() {
  // 'this' is a jQuery object at this point - with all the jQuery functions
  return this.each(function() { // return so we don't break the chain
    // now we are inside of a jQuery function, the DOM element is the context
    // so 'this' has changed to become a DOM element.
    if (this.host != window.location.host) {
      $(this).attr('target', '_new');
    }
  });
};

Finishing up

This is far from comprehensive, but equally there's very little to the logic. So long as you remember the context of 'this' changes when moving in and out of object methods then you're on your way.

If you're still not sure, get your hands on Firebug and add 'console.log(this)' within your code to interrogate and understand what 'this' is at that point in your code.

If this still doesn't make sense or I've got it terribly wrong - or you're suddenly enlightened, please do let me know - and I'll do my best to help.

Sunday, March 7, 2010

HTML5

Some have embraced it, some have discarded it as too far in the future, and some have abandoned a misused friend in favor of an old flame in preparation. Whatever side of the debate you’re on, you’ve most likely heard all the blogging chatter surrounding the “new hotness” that is HTML5. It’s everywhere, it’s coming, and you want to know everything you can before it’s old news.

Things like jQuery plugins, formatting techniques, and design trends change very quickly throughout the Web community. And for the most part we’ve all accepted that some of the things we learn today can be obsolete tomorrow, but that’s the nature of our industry.

When looking for some stability, we can usually turn to the code itself as it tends to stay unchanged for a long time (relatively speaking). So when something comes along and changes our code, it’s a big deal; and there are going to be some growing pains we’ll have to work through. Luckily, rumor has it, that we have one less change to worry about.

In this article, I’m hoping to give you some tips and insight into HTML5 to help ease the inevitable pain that comes with transitioning to a slightly different syntax.

Welcome to HTML5.

Html5 Logo in HTML5 and The Future of the Web

[Offtopic: by the way, did you know that Smashing Magazine has one of the most influential and popular Twitter accounts? Join our discussions and get updates about useful tools and resources — follow us on Twitter!]

What are the basics?

The DOCTYPE

When I first started researching HTML5 a few months ago, one of the main things I struggled to find was the doctype. A simple thing, you’d think it would be everywhere, but after much frustration, I finally found it buried within w3.org and here it is:

1<!DOCTYPE html>

I was also curious why they chose to “html” rather than “html5″, it seemed like the logical way to tell a browser that the current document was written in HTML5, and offered a good template for the future. But I found that <!DOCTYPE html5> triggers Quirks Mode in IE6, and when taking backwards compatibility into consideration <!DOCTYPE html> is a pretty good choice (in my opinion).

Overall, I really like the new DOCTYPE; it’s small, meaningful, and maybe we’ll actually be able to remember this one by heart and not have to paste it from site to site.

New Elements you should know

At first glance, with HTML5, the new elements immediately jump out and command attention. The W3C really listened to the community and planned for the future when architecting the abundance of new elements available. We have everything from basic structural elements like <header> and <footer> to others like <canvas> and <audio> that tap into, what seems to be, a very powerful API which allows us the freedom to create more user-friendly applications while further distancing ourselves from reliance on Flash for saving data and intense animation.

The new structural elements
  • <header>
    The header element contains introductory information to a section or page. This can involve anything from our normal documents headers (branding information) to an entire table of contents.
  • <nav>
    The nav element is reserved for a section of a document that contains links to other pages or links to sections of the same page. Not all link groups need to be contained within the <nav> element, just primary navigation.
  • <section>
    The section element represents a generic document or application section. It acts much the same way a <div> does by separating off a portion of the document.
  • <article>
    The article element represents a portion of a page which can stand alone such as: a blog post, a forum entry, user submitted comments or any independent item of content.
  • <aside>
    Aside, represents content related to the main area of the document. This is usually expressed in sidebars that contain elements like related posts, tag clouds, etc. They can also be used for pull quotes.
  • <footer>
    The footer element is for marking up the footer of, not only the current page, but each section contained in the page. So, it’s very likely that you’ll be using the <footer> element multiple times within one page.

When you take a look at these new elements, it looks like they’re just replacing our common DIV IDs; and in a way, it’s true. But, the diagram below shows that elements like <header> and <footer> can be used more than once on a single page where they behave more like classes and normal HTML elements that you can use over and over again to retain a semantic structure.

Html5 Structure in HTML5 and The Future of the Web

Elements like <header> and <footer> are not just meant to represent the top and bottom of the current document, but they also represent the <header> and <footer> of each document section, much the way we use <thead> and <tfoot> in data tables.

The benefits of using these structural elements is mainly due to the fact that they are extremely well defined and provide a great way to semantically structure your document. However, these elements do need to be used with some careful thought because they can, very easily be overused.

Further Reading on structural HTML5

Easing the transition from XHTML

Even though HTML 4.01, XHTML 1.0, & HTML5 are all very similar there are some small syntax differences that can, very easily, slip past anyone and invalidate code. Keeping this in mind, HTML5 has some built-in “slack” to make the transition a little easier.

For example, when marking up a form in HTML5, this is the proper syntax for an input text element:

1<input type="text" id="name">

But this is also accepted as valid code in an attempt to ease the pain for avid XHTML coders (like myself) who are used to self-closing elements:

1<input type="text" id="name"/>

The same rules apply to <meta> and other self closing elements. Legacy elements like <b> and <i> were also left in to help those coming over from HTML 4.01.l

What are the benefits?

With any new technology there has to be benefit; why else would you use it? If your old code works just as well and efficient as the new code there’s no reason to upgrade. No reason at all, trust me, I checked.

Luckily HTML5 is packed with cool new features, code slimming techniques and a lot of stuff I would call very large benefits. Most of which circle around the new APIs and the DOM tree.

Extending the API

The most obvious benefit built into HTML5 is the numerous APIs and the opportunities it opens up for the future of web apps with Holy Grail of application cache and offline capabilities. Google Gears gave us offline data storage and Flash introduced us to the power of application cache (Pandora uses it to save your log in information). With HTML5, these capabilities are now available to use right in the language and can easily be expanded with JavaScript.

HTML5 relies on light scripting to flex its muscles on the Web; this is very possibly the first time, other than jQuery, that one (front-end) technology has fully acknowledged another. Sure, we connect them with classes and IDs but up until now, they have been perceived as separate layers by the principles of progressive enhancement. But as the Web grows we need unity like this across the Web.

Html5 Api in HTML5 and The Future of the Web

Offline Data Storage

The coolest part about HTML5 is definitely its offline capabilities. Programs like Thunderbird and Outlook (and now GMail to an extent) let you browse through your old data while staying offline. With HTML5, you’ll have this same functionality, but in the browser. This is the first serious step towards bridging the gap between the desktop and the Web, and opens all sorts of doors for the future of Web apps.

The W3C has taken the best parts from the various Web technologies and rolled them into, what is being dubbed the most powerful markup language to date.

Some other of the HTML5 APIs
  • Drag & Drop
    The drag and drop API defines an event-based drag and drop system. However, it never defines what “drag and drop” is. This API requires JavaScript to fully work as normal think drag and drop functionality.
  • Video & Audio
    The audio & video APIs are massive upgrades in media embedding. Although support is limited right now, something like video embedding has never been easier:
    1<video width="400" height="360" src="vid.mp4">
  • Geolocation
    Geolocation is a very cool API available within HTML5. Its object can be used to programmatically determine location information through a device’s user agent (hint hint: mobile devices).
Further reading on the HTML5 API

Where can I use it?

Even with the very limited support for HTML5, the Web is far too progressive to not create a testing environment for us to play around. Currently, Safari is our best testing platform, as it supports most of the new elements and APIs. Of course, that may change at anytime so keep and eye on Opera, Chrome and Firefox as well.

Normally you might think since Safari is a Webkit browser, by default, all Webkit browsers would support the same elements, unfortunately, this isn’t the case. While many of the HTML5 features are supported across the board in Webkit browsers, there are some, like <video>, that are not.

Mobile devices

To effectively use HTML5 right now, we need to be able to control the environment in which it is used. Since support is not as widespread as we’d like it doesn’t make real sense for it to be heavily used unless, of course, we can lock down the usage to certain platforms which have HTML5 support. With Webkit leading the way for HTML5, we can safely focus on devices powered by Webkit.

Mobile Phones in HTML5 and The Future of the Web

The 3 hottest mobile devices right now: The Palm Pre, iPhone 3Gs and the new Google Android phone all have browsers that are based off the Webkit rendering engine.

Safari is even leading the way on the mobile HTML5 front; The iPhone (with the latest software upgrade) is the only device I could get to properly render the <audio> element. Because these devices are so young and all use the same rendering engine, the likelihood of them pushing a rapid software upgrade is pretty high.

Right now, you can confidently use many of the HTML5 features in iPhone Web app development and mostly likely expect Pre and Android to follow in suit.

Further reading on where you can use HTML5

How can we move forward?

Even with all the recent hype surrounding HTML5 and how we all want to use it, it is still going to be a very slow transition away from HTML4.01 & XHTML1.0. It will take time to get developers up to speed, test all the features, waiting for all the :ahem: browsers to catch up, and it will take an especially long time for users to transition out of those old browsers. With all that in mind, we know who we are, we’re all reading this article (I’ve read it about 30 times so far) and we know we have to find a legitimate way to move forward without damaging the past.

We can’t make the full switch yet and there’s no use at this point pointing out who is holding up the show. We all know that any responsible developer would not drop support for a browser that is still heavily used. So rather than yell at a brick wall, here are some things I’ve found that might help us move forward in a positive way:

Semantic DIV naming

Semantically aligning your DIV names with that of the new HTML5 elements will help you get used to the names themselves and also the new functionality and nesting that they want you to do with the <header> and <footer> elements. These are akin to learning the intro to Enter Sandman (for the guitarist out there); it’s not very difficult, but it takes a little practice to get it to feel natural.

Before jumping in full-force to HTML5 production sites, I recommend trying the soft transition with changing your DIV names slightly. There’s no downside that I’ve found to doing this, you can even use the new DOCTYPE with very little consequence.

Faking it with JavaScript

First off, I’d like to say: Please don’t do this in production. If the client side scripting fails, it will completely collapse the site in browsers that won’t take CSS applied to the new elements. This is simply not a good option. It is, however, an option and I’m all about knowing your options no matter what they are.

Creating the new elements with JavaScript

Working in jQuery is cool and all, but as it turns out, there is a built in function to JavaScript to deal with creating new elements:

document.createElement('header');
document.createElement('footer');
document.createElement('section');
document.createElement('aside');
document.createElement('nav');
document.createElement('article');
document.createElement('figure');
document.createElement('time');

…and so on in that fashion.

This will allow you to style these elements in Internet Explorer. Again, the downside of using this technique is that, without the all-important JavaScript, the site will not only be unstyled, all the unrecognized elements will default to inline. So your site will literally collapse on itself.

Client side JavaScript is not the answer for using HTML5. Server side javascript, now that’s a completely different story…

Building browser-specific apps

I’ve always promoted building sites for your audience, so depending on your audience, building browser-specific applications may be a real option. As I mentioned above, it’s all about controlling the environment, if we can control the environment we can control features delivered to the user much better. Google is currently attempting to do this with Google Wave.

The idea behind Google’s new monster product is to revolutionize communication, and do so with the newest technology. Google Wave is built in HTML5 and isn’t usable in all browsers yet. But that’s alright since they’re controlling the audience by only releasing it to select developers for testing.

Google Wave in HTML5 and The Future of the Web

With Wave, Google is pushing HTML5 as far as it will go (and even a little further). They are taking blogs, wikis, instant messaging, e-mail and synchronous communication to the next level by combining them into place.

Here is what the Wave inbox looks like.

Google Wave Inbox in HTML5 and The Future of the Web

Below is a sort of wiki/chat area with all sorts of real-time communication treats for you to check out (once they release it).

Google Wave Inline Editing in HTML5 and The Future of the Web

Google Wave being powered by HTML5 is definitely the biggest step forward we have seen in this area. They have done a phenomenal job putting together a creative and innovative product.

Focusing on the mobile

Just like Google is currently doing with Wave by selectively releasing it to developers, we can control the viewing environment when working with mobile devices. By grabbing the user agent, we can design specific applications that use HTML5 for supported devices.

Targeting the user agent of a device is not an ideal method in designing for the general mobile web, but when we need to specifically target a device, like the iPhone, Pre or Google’s Android it’s a pretty solid option.

Right now, the best mobile testing platform we have is the iPhone. With the recent software upgrade, it is very close to having full support. But, if you just want to use the new elements, most any of the big 3 mobile platforms will work fine. If you’re looking for API support I suggest testing on the iPhone with the new upgraded software.

Conclusion

With the strong foundations set up by previous versions of (X)HTML and large community activity surrounding Web standards, we’re coming into a new age with a wealth of knowledge and the ability to learn from our past mistakes (and make some new ones). HTML5 is being set up with the expectations of a very powerful markup language and it’s up to us to utilize it in a way that can benefit us all.

There are so many great features to look forward to from new elements to tons of killer APIs. We can make data available offline, easily combine technologies and create very intricate animations all within a familiar landscape. If you have the time, I encourage you to browse through the entire spec and familiarize yourself even further with all the bells and whistles (there are a lot) so we can use HTML5 to build stronger, richer Web applications for years to come.

Here’s to HTML5, let’s hope it lives up to the hype.

Resources

  • 23 Essential HTML 5 Resources
    A comprehensive list of articles and resources related to HTML 5.Ess in HTML5 and The Future of the Web
  • HTML5 Demos
    HTML5 Demos is a great resource for checking out the HTML5 APIs such as: geolocation, drag and drop, offline detection, and storage. This is a very good and unique resources to test out and see exactly with we can do with HTML5.1 in HTML5 and The Future of the Web
  • HTML5 Gallery
    The HTML5 Gallery, like any gallery, is a web site showcase where you can see how others are using HTML5 in every day development. I’ve looked round though this site quite a bit and did some cross browser testing on some of the entries. Many are broken in older browsers, but there are some that hold up very well.Html5g in HTML5 and The Future of the Web
  • HTML5 Doctor
    A resource that catered for the people who wished to find out more about implementing HTML5 and how to go about it. This blog publishes articles relating to HTML5 and it’s semantics and how to use them, here and now.Doctor in HTML5 and The Future of the Web
  • HTML5 Cheat Sheet
    A handy printable HTML 5 Cheat Sheet that lists all currently supported tags, their descriptions, their attributes and their support in HTML 4. Released here, at Smashing Magazine.Html5 in HTML5 and The Future of the Web
  • W3C HTML5 Spec Overview
    Whenever you want to know
    about something that no one has written about on the Web, the W3C is your answer. I spent hours scouring this site in researching HTML5. It’s a great resource and I highly recommend reading through whatever you can.
  • HTML5 Validator
    Even with such little support, we still want to make sure our code is valid. Validating your code is a great way to learn and ease yourself into developing with HTML5.
  • WHATWG Wiki
    The HTML Working Group has put together some great documentation for tracking what exactly is going on in the world of HTML5.

References

Sunday, February 14, 2010

JavaScript Unit Testing and Continuous Integration with JsTestDriver

I am currently reworking the JavaScript layer of an application at work. Among several initiatives to improve the maintainability of the app, I suggested to adopt JavaScript unit testing. There are several JavaScript unit testing framework out there. The one that I used before was QUnit, a simple unit test framework developed by the jQuery team and I intended to use it again.

The final goal was to have our tests ran within our continuous integration process, meaning the JS tests would run when a build was scheduled.

My initial approach was to write:

  1. QUnit tests and called the script from a single file.
  2. Generate an automated test with Selenium to read the result section of the QUnit result page
  3. Depending on what was read, fail or pass the test like any other JUnit tests.

Simple enough until a coworker briefly mentioned to me JsTestDriver.

What is JsTestDriver?

JsTestDriver is a JavaScript testing framework supported by Google. It is more complete than a JavaScript Unit Testing library and can provide you with the following benefits:

  • provides JavaScript Testing API similar to JUnit. You can also write tests against the DOM very easily.
  • can be run via the command line: this means it can be integrated to your Continuous Integration process.
  • can output test results in the same XML format as JUnit results tests: this will allow you to produce reports on the last build and run of tests suites.
  • can provide code coverage.
  • has an eclipse plug-in to run the tests. The plugin is very enjoyable to use because you can run your tests against any browser you specify without leaving leaving Eclipse. With QUnit, you would have to open each browser and refresh the page every time you make a code change for each browser you test against.
  • last but not least, it exists adapters for other JS testing framework so that you can run your tests using JsTestDriver even if you used another testing library such as QUnit.

As you can see, JsTestDriver and its plugins offer a much more complete set of tools to write and automate JS testing.

I was somewhat reluctant at switching from QUnit (which I thought was good enough) to JsTestDriver. However I realized QUnit was only a part (but essential nonetheless) of the whole JS testing process.

Where to I get started?

I will not write today a tutorial on using JsTestDriver, maybe later. I will just point out the resources to get a better feel for it.

1. A presentation video: http://www.youtube.com/watch?v=aDKGGZv-T4M

2. The google code website: http://code.google.com/p/js-test-driver/

To break down the jsTestDriver site and I am linking each of the above points (in the what is JsTestDriver section) to its corresponding page for more info.

There are a few other topics such as how to debug (which is the same as you would debug a JS script with Firebug) and the config file (very simple).

I hope this gave you an idea of JsTestDriver. Hopefully I will post an example soon.