Ever heard of Shadow DOM? If you haven’t then this article is definitely for you (and if you already have, you should still read this ;)).

Despite of the “scary” name it has there’s nothing to be afraid of. Shadow DOM is a friendly little fellow who’s here to make life of web application developers easier.

In this article, I’ll present thoroughly the capabilities of Shadow DOM and how one can easily create independent widgets by encapsulating their code with it.

Table of Contents

Prerequisites

At the moment, Shadow DOM API can only be used and accessed with Chrome 25+ Beta or Chrome Canary. Download either one of them and start inspecting what Shadow DOM has to offer.

To access Shadow DOM via Chrome Console, you have to enable it from Settings -> General -> [x] Show Shadow DOM.

What is it About?

Shadow DOM is described by W3C as “The shadow DOM allows multiple DOM trees to be composed into one larger tree when rendered”. In practice, this means that it’s possible to create shadow roots and include them into document tree nodes, better known as shadow hosts. Shadow roots can contain child nodes, and these nodes aren’t exposed in traditional DOM tree at all.

Let’s have an example: suppose we have an input element which type is date. In modern browsers this type of element contains a date picker to provide some additional functionality and accessibility for the user.

This is where Shadow DOM enters the stage: date picker is constructed as a Shadow DOM subtree where input field acts as an shadow host.

Even though we can view the Shadow DOM of browser components, we can’t directly access to them.

Playing with Shadow DOM

Now that you’ve set up and you understand the basics about Shadow DOM, it’s time to start playing with it.

In our case, we want to create a simple custom widget which displays JSON data structure in a table. I won’t go in to the deepest details of the widget, but I’ve created a live demo of the widget I’m using as an example.

Preparing Content

At first we start by preparing and creating content. There are couple of guidelines on creating content:

  • it may be wise to use HTML templates instead of direct DOM manipulation when creating complex structures,
  • avoid using too generic naming. Although Shadow DOM is secured, this can lead to misunderstandings,
  • using pseudo-attributes is a good practice

With these guidelines we make the life easier both for us and for the developers who are using the widget.

We start by creating a template for our widget:


Notice: if you want to use external template files (like I do in my demo), use valid HTML elements, eg. by switching template element to a section.

Now we have a basic HTML structure set up and we can add some styling:


This is it. We have a HTML structure and CSS styling ready for the widget and now we need to do some JavaScript magic. Basically we want to fetch the template elements and use them as shadow root children elements for displaying the JSON data. In order do to this, we need some attributes for the jsontable element:


What we’ve got here is:

  • jsontable as the custom widget element,
  • data-template refers to an id of the template we want to use,
  • data-source refers to a JS object variable which contains the “JSON data”

There are both static and XHR examples in my demo, check them out for further guidance of using the data-source and .dataSource setter.

Creating a Shadow Root

We will start by accessing our custom HTML element called <jsontable> and creating a shadow root for it by calling document.webkitCreateShadowRoot (notice the webkit prefix):

var jsontable = document.querySelector("jsontable"),
    jsontableRoot = jsontable.webkitCreateShadowRoot();

For the simplicity of this example, we access only one jsontable element at time and create the functionality for it.

Next, we need to refer to our template and append it to the shadow root:

var templateId = jsontable.dataset.template;
var templateNode = document.getElementById(templateId);

jsontableRoot.appendChild(templateNode);

After this, following steps are:

  • setting references for template elements (table, tr, th, td),
  • populating table from the JSON by using these references

Both of these steps are done in my live demo I’ve created for this article.

This is it! What we’ve achieved is an independent widget which doesn’t interfere with the other DOM at all.

Accessing Shadow Root

Sometimes, one may need to access Shadow DOM externally and manipulate it. This is possible both with CSS and JS.

Accessing via CSS

In order to allow CSS access, we need to declare <shadow root>.applyAuthorStyles = true;. In our example, I made a setter for it (see live demo for further details):

var exports = {
    set applyAuthorStyles(x) {
        jsontableRoot.applyAuthorStyles = !!x;
    }
};

This allows accessing the styling whenever we need to, ie. we can enable and disable in on the fly.

Accessing via JavaScript

JavaScript access can’t be done with direct reference (see example), but it can be done by using webkitShadowRoot property, eg.:

var table = document.querySelector("jsontable").webkitShadowRoot.querySelector("table");

This allows manipulating the Shadow DOM whenever it’s needed. At the moment it’s not even possible to protect your Shadow DOM from external access (see Bug 16509 – [Shadow]: Consider isolation).

Conclusions

I’ve to say I’m excited about Shadow DOM. Although different kinds of snippets, plugins and widgets have been created for years, Shadow DOM and Web Components offers a clear path for creating eg. custom form controls, media controls, captchas, etc.

Current status of course is that Shadow DOM can’t yet be used purely because it has landed only on few browsers and the work is still in progress. However, we can play it with (just like we did in this article) and consider the possibilities it offers in the future.

Resources

Here are some of the resources I encountered while exploring the wonderful world of Shadow DOM:

The final version of iOS 5 has been finally released and there’s lots of buzz going around it’s new features. Most of the discussion focuses on the operating system itself which is totally understandable. There are lots of improvements and nifty little features to play with.

But one thing that seems not to get such attention is what iOS 5 brings to us, web developers, and how it improves the experience with web applications.

In this article I’ll go through most of the major features that are included in iOS 5 for web developer point-of-view.

Table of Contents

-webkit-overflow-scrolling

This is probably most anticipated feature for web applications. Until today it hasn’t been easily possible to add scrollable content in web document.

Briefly, all you need to define is:
elem {
 overflow:scroll;
 -webkit-overflow-scrolling:touch;
}

To achieve proper scrolling support for iOS 4 and/or other devices, I strongly suggest using iScroll 4.

And if you want to display scrollbars all the time, read this post: Force Lion’s scrollbar back. It will help you on displaying the scrollbar while user is not accessing the scrollable area, which is a very good visual guidance for user that content can be scrolled. But be warned: “custom” scrollbar won’t update it’s location while user is scrolling and meantime there are two scrollbars displayed.

position:fixed

Position:fixed is well-known CSS property that hasn’t earlier been included in iOS. But now it’s there, ready to use.

I noticed that setting a fixed element it has partial transparency by default. You even can’t turn it off by setting opacity to 1.0. If you happen to know how to solve this, please comment on my blog.

New Input Types

iOS5 provides several new input types that didn’t exist earlier on iOS4. These input types are: date, time, datetime, month and range.

I have to mention that the user experience with range is awful – with your (fat) finger you end up selecting the whole control instead of value slider all the time.

Note: input type=”file” isn’t still working. “Choose File” button is displayed, but at the same time it’s disabled.

WOFF Font Support

iOS 5 supports WOFF (Web Open Font Format) fonts. This is good news in a way. I haven’t personally tested whether there’s any benefit compared to SVG or TTF from a rendering or performance point-of-view.

Web Workers

Web Workers API is a bit less familiar for many developers. They allow to run long-running scripts without halting the user interface and they’re not interrupted by other actions.

The problem with Web Workers on iOS 5 is – as you may guess – the perfomance. You can try Web Workers with Javascript Web Workers Test. But I have to mention that while it took only about five seconds with my workstation, the same execution time with my iPhone 4 was 106 seconds. So as you can see, there’s a huge difference on performance.

contentEditable

iOS 5 supports contentEditable attribute, which allows rich text editing (RTE) of content. This is very welcomed feature offering the possibility of building WYSIWYG editors that can be used eg. with iPad.

Read more about this feature at: WYSIWYG Editing (contentEditable support) in iOS 5.

classList API

ClassList API is very useful while writing native JavaScript. It has few simple functions (like add(), remove(), toggle()) that are meant for handling classNames in an element.

If you want to implement classList API and ensure backwards compatibility, use classList.js polyfill, written by Eli Grey.

matchMedia()

Function matchMedia() is relatively new function for detecting media queries with JavaScript. The implementation is very simple:

if (matchMedia("(min-width: 1024px)").matches) {
    alert('your screen is at least 1024px wide');
}
else {
    alert('your screen is less than 1024px wide');
}

Can’t say how useful that is yet, since I’ve personally never used it before. But we’re living the times of Responsive Web Design and there may be conditions where this may be needed.

For browsers that doesn’t support matchMedia(), there is a matchMedia.js polyfill available, written by Paul Irish.

And if you’re more interested in similar logic, I suggest reading about yepnope.js.

Changes in Gestures Events

Gestures events (gesturestart, gesturechange, gestureend) now returns pageX and pageY values for events – in addition to scale and rotate values. These values didn’t exist in iOS4, forcing developer to retrieve X/Y-coordinates with corresponding touch events.

Compass

iOS 5 comes also with two neat properties: webkitCompassHeading and webkitCompassAccuracy. You can read more about them and test them at: Taking a new device API for a spin.

WebGL

Well… WebGL is kind of implemented in iOS5. But only for iAd.

However there are rumors promising good, and already it’s said that “things are in place” but they’re just not fully working (or have been disabled). So, let’s keep our fingers crossed that next (minor) update will include support for WebGL.

Anything Else?

Mark Hammonds has written a comprehensive article in mobiletuts+, titled iOS 5 for Web Devs: Safari Mobile Updates. That’s really worth of reading!

And if you’re interested in browser performance in general, then you should read iOS 5 Top 10 Browser Performance Changes.

If there are other things to mention, feel free to comment and bring your ideas up. I’ll keep on updating this post right after new information arises about iOS 5.

It doesn’t matter how many years I’ve been dealing with Javascript – it contains many little things that surprises me almost every week. For me, Javascript means a constant learning process.

In this article, I’ll provide ten small Javascript tips, mainly aimed for beginner and intermediate Javascript developers. Hopefully there’s at least one useful tip for every reader :).

1. Variables conversions

This sounds quite obvious, but as far I’ve seen, using object constructors, like Array() or Number() for converting variables is quite common practice. Always use primitive data types (sometimes referred as literals) for converting variables. These won’t do any extra tricks and they usually have better performance.
var myVar	= "3.14159",
	str		= ""+ myVar,//	to string
	int		= ~~myVar,	//	to integer
	float	= 1*myVar,	//	to float
	bool	= !!myVar,	/*	to boolean - any string with length
							and any number except 0 are true */
	array	= [myVar];	//	to array
Converting to dates (new Date(myVar)) and regular expressions (new RegExp(myVar)) must be done with constructors. However, always use /pattern/flags when creating regular expressions.

2. Converting decimals to hex or octals and vice versa

Are you writing separate functions for hex (or octal) conversios? Stop. This can be easily done with existing methods:
(int).toString(16);	// converts int to hex, eg 12 => "C"
(int).toString(8);	// converts int to octal, eg. 12 => "14"
parseInt(string, 16) // converts hex to int, eg. "FF" => 255
parseInt(string, 8) // converts octal to int, eg. "20" => 16

3. More playing with numbers

In addition to previous section, here are some more small tricks with when dealing with numbers.
0xFF; // Hex declaration, returns 255
020; // Octal declaration, returns 16
1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000
(1000).toExponential(); // Opposite with previous, returns 1e3
(3.1415).toFixed(3); // Rounding the number, returns "3.142"

4. Javascript Version Detection

Are you aware which version of Javascript your browser supports? If not, check Javascript Versions sheet from Wikipedia. For some reason, features in Javascript version 1.7 are not widely supported. However, most browsers released within a year support features in version 1.8 (and in 1.8.1). Note: all the versions of Internet Explorer (8 and older) supports only Javascript version 1.5. Here’s a tiny script both for detecting the version of Javascript via feature detection. It also allows checking support for specific version of Javascript:
var JS_ver	= [];

(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;

JS_ver.supports	= function()
{
	if (arguments[0])
		return (!!~this.join().indexOf(arguments[0] +",") +",");
	else
		return (this[this.length-1]);
}

alert("Latest Javascript version supported: "+ JS_ver.supports());
alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));

5. window.name for simple session handling

This one is something I really like. You can assign values as a string for window.name property and it preserves the values until you close the tab or window. Although I’m not providing any script, I strongly suggest you to take full advantage from it. For instance, it’s very useful for toggling between debugging and (perfomance) testing modes, when building a website or an application.

6. Testing existence of property

This issue can be approached at least from two directions. Either we check whether property exists or we check the type of property. But always avoid these small mistakes:
// BAD: This will cause an error in code when foo is undefined
if (foo) {
	doSomething();
} 

// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
	doSomething();
}

// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {
	doSomething();
}
However, there may be situations, when we have deeper structure and proper checking would look like this:
// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
	doSomething();
}

7. Passing arguments for function

When function has both required and optional parameters (arguments), eventually we may end up with functions and function calls looking like this:
function doSomething(arg0, arg1, arg2, arg3, arg4) {
...
}

doSomething('', 'foo', 5, [], false);
It’s always easier to pass only one object instead of several arguments:
function doSomething() {
	// Leaves the function if nothing is passed
	if (!arguments[0]) {
		return false;
	}
	
	var oArgs	= arguments[0]
		arg0	= oArgs.arg0 || "",
		arg1	= oArgs.arg1 || "",
		arg2	= oArgs.arg2 || 0,
		arg3	= oArgs.arg3 || [],
		arg4	= oArgs.arg4 || false;
}

doSomething({
	arg1	: "foo",
	arg2	: 5,
	arg4	: false
});
This is only a rough example of passing an object as an argument. For instance, we could declare an object with name of the variable as keys and default values as properties (and/or data types).

8. Using document.createDocumentFragment()

You may need to dynamically append multiple elements into document. However, appending them directly into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you should use document fragments, which are appended only once after completion:
function createList() {
	var aLI	= ["first item", "second item", "third item",
		"fourth item", "fith item"];
	
	// Creates the fragment
	var oFrag	= document.createDocumentFragment();
	
	while (aLI.length) {
		var oLI	= document.createElement("li");
		
		// Removes the first item from array and appends it
		// as a text node to LI element
		oLI.appendChild(document.createTextNode(aLI.shift()));
		oFrag.appendChild(oLI);
	}
	
	document.getElementById('myUL').appendChild(oFrag);
}

9. Passing a function for replace() method

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this would be passing a separate function for method String.replace(). Following example is a rough implementation of making a more verbose output from a single deal in online poker:
var sFlop	= "Flop: [Ah] [Ks] [7c]";
var aValues	= {"A":"Ace","K":"King",7:"Seven"};
var aSuits	= {"h":"Hearts","s":"Spades",
			"d":"Diamonds","c":"Clubs"};

sFlop	= sFlop.replace(/\[\w+\]/gi, function(match) {
	match	= match.replace(match[2], aSuits[match[2]]);
	match	= match.replace(match[1], aValues[match[1]] +" of ");

	return match;
});

// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10. Labeling of loops (iterations)

Sometimes, you may have iterations inside iterations and you may want to exit between looping. This can be done by labeling:
outerloop:
for (var iI=0;iI<5;iI++) {
	if (somethingIsTrue()) {
		// Breaks the outer loop iteration
		break outerloop;
	}
	
	innerloop:
	for (var iA=0;iA<5;iA++) {
		if (somethingElseIsTrue()) {
			// Breaks the inner loop iteration
			break innerloop;
		}

	}
}

Afterwords

Go ahead and comment! Did you learn anything new? Do you have good tips to share? I'm always delighted for sharing information about all the little details in Javascript. And if you want to familiarize with Javascript irregularities, I suggest you visiting at wtfjs :).

UPDATE

This project is updated! Visit the GitHub Project Page for details.


I was about not to publish anything before Christmas – just calming down, taking some extra time to get my blog design finished, plugins installed, and so on..

..but no. I got way too excited when I heard today that Opera 10.5 pre-alpha for Labs was released. In other words, this means that an updated version of Opera’s layout engine, Presto, was out to play with – meaning, that CSS3 Transformations and Transitions are available also for Opera.

In this article, we write some lines of CSS and create rotating transform effect with all the common browsers, including Internet Explorer and the latest version of Opera.

Issues with Opera and IE

Opera offers CSS3 Transitions support in Opera Presto 2.3, at least partially. By the specification, we’re able to take advantage of -o-transform:rotate(deg);.

IE is a bit trickier (big surprise). Fortunately there’s a nice filter available, called Matrix. The values for matrix are quite complicated, hence some assistance with Javascript is needed.

In my case, I’ve created some functionality and bound it with HTC file to CSS selectors. The functionality is based on values of property -ms-transformation. I’ve also implemented -ms-transition for transitions, but this will be examined further on later posts.

Example code

In this example, I’ll be using A-elements for hover support in IE6. I’ve already written a small implementation similar to Whatever:hover, but that “project” is still taking baby steps.

So let’s cut the chase and create some lines of code:

HTML

<a href="#" id="one" class="rotate">This is 45deg -rotated element.</a>
<a href="#" id="two" class="rotate">This is 10deg -rotated element, which rotates to 45deg when hovered.</a>

CSS

#one	{
  behavior:url(-ms-transform.htc);
  -moz-transform:rotate(45deg);
  -webkit-transform:rotate(45deg);
  -o-transform:rotate(45deg);
  -ms-transform:rotate(45deg);
}
#two	{
  behavior:url(-ms-transform.htc);
  -moz-transform:rotate(10deg);
  -webkit-transform:rotate(10deg);
  -o-transform:rotate(10deg);
  -ms-transform:rotate(10deg);
}
#two:hover	{
  -moz-transform:rotate(45deg);
  -webkit-transform:rotate(45deg);
  -o-transform:rotate(45deg);
  -ms-transform:rotate(45deg);
}

Demo

You can view demo at Demo section: Cross-browser Rotation Transformation with CSS.

Final thoughts

Although everything “is not fully there”, this article shows the possibility for implementing cross-browser CSS3 Transformations purely with CSS.

In addition, this post works as an opening post of my blog. Feel free to give feedback. Merry Christmas!