JavaScript Fatigue

An old developer’s take on JavaScript fatigue:

Old guy yells at young whippersnappers: Get your JavaScript fatigue off my lawn or I’ll whoop your ASCII!

Read the article.

CSS Flexbox Grids for Your Apps

ChocolateChip-UI provides a convenient grid system based on CSS flexbox. This means your grid columns use flex to determine their widths. This gives you responsive layouts. Because the grids use flexbox, there are no floats involved, and no need to clear floats, etc. Also all columns are automatically equal height in the same grid.

To make a grid, just put the class grid on a div:

// Define a grid:
<div class='grid'></div>

This gives you a grid row. Inside this you can create grid columns with the class col.

// Define a grid with 3 columns:
<div class='grid'>
   <div class='col'>1</div>
   <div class='col'>2</div>
   <div class='col'>3</div>
</div>

By default all columns have a flex value of 1, so they will all have the same width. You can give columns a specific flex value using specific classes that ChocolateChip-UI uses. These are as follows:

<div class='flex-1'></div>
<div class='flex-2'></div>
<div class='flex-3'></div>
<div class='flex-4'></div>
<div class='flex-5'></div>
<div class='flex-6'></div>
<div class='flex-7'></div>
<div class='flex-8'></div>
<div class='flex-9'></div>
<div class='flex-10'></div>

 

Live Example using “flex-1”

By giving columns various flex values you can create complex layouts for you app

 

Columns Based on Total Flex Value of 10

 

Equal Height Columns

As we mentioned, columns in the same grid row are always equal height.

 

Column Gutters

You can give your grid, both rows and columns, some preset gutters. To do so you can put one of two classes on the grid row: gutter-5 or gutter-10.

 

If you want some other gutter value, you can create your own class. Below is a possible class you could use:

.gutter-15 {
   margin: 15px;
}

Then you can use your class on your grids like with our own gutter classes.

Centered Grids

You can center the columns to the grid row, creating space around them, using the center class:

 

Fixed Width Columns

By their nature, flex columns are dynamic. They flex to fill whatever space is available on screen. This is great for mobile devices, such as when the user changes the orientation of a mobile device from portrait to landscape. You can rest assure that you layout will work equally well in all situations. However, sometimes you may need to give a particular column a fixed width. You can do this by giving it a special class. On this class you will define the width you want, and you will also set its flex value to 0:

.fixedWidth {
  -webkit-flex: none;
  flex: none;
  width: 250px;
}

Putting the above class on a column will force it to always have a width of 250 pixels. Any other columns in its grid row will use whatever space is left after that column is rendered. Below is an example of fixed columns:

 

Learning About Layout in ChocolateChip-UI

To learn more about layouts in ChocolateChip-UI, visit the following links:

ChocolateChip-UI 4

So, after a lot of thought, we decided to push a lot of the features of TruckJS to ChocolateChip-UI. Why? Because of the brand. So many people were already using ChocolateChip-UI and it’s been out for four years.

To learn more about the new version, visit the website at ChocolateChip-UI.Github.io

At the same time, we didn’t want to make the move from 3 to 4 too drastic for people used to the earlier version of ChocolateChip-UI. So we went back and simplified some of the things we were doing in TruckJS. The result is ChocolateChip-UI 4. All the layouts and widgets you need to make a mobile app quick. But we moved the heavy lift out of the ChocolateChip-UI Github repository and instead completely redid our NPM module Chui. Chui is now at version 2. It now is the main way you create your ChocolateChip-UI apps. It also lets you output all the ChocolateChip-UI examples to your desktop, as well as four references apps that show you how to create apps with plain JavaScript or with ES6 modules and a build step. It can also turn your app into a hybrid app to iOS and Android. It’s your one tool for everything you need to build your app.

You install Chui with the following NPM command:

 npm install -g chui

To learn more about Chui, visit the NPM page or read the install instructions at ChocolateChip-UI.Github.io.

From ChocolateChip-UI to TruckJS

It all started with a simple DOM library for mobile use. I named it ChocolateChip, because I liked chocolate a lot and because if was really small.

On this blog, one post after another, I created prototypes of how to replicate iOS with markup, CSS and some JavaScript. After many posts I had the makings of a framework. These were all random, so I needed to bundle it all together. ChocolateChip was the glue, so I named the framework ChocolateChip-UI. That was six years ago.

As time passed, ChocolateChip-UI grew to accommodate new layouts, widgets and support for Android and Windows Phone, and could switch out to use jQuery. And then we made jQuery the default. So many changes…

Recently I was thinking about where to take ChocolateChip-UI. It seemed like it had everything it needed. I went and got some specialty chocolates and some good coffee and sat down to brood. I thought about the difference between Backbone and Angular. Backbone at least had models, where as Angular does not. Because of that, Angular has to run constant polls to compare the state of the raw JavaScript objects. The more you use Angular’s data binding, the more polls you have going and everything starts slowing down, especially on mobile.

In a system with models, it’s the model’s responsibility to inform the system when its data is modified. The system does not need to be running polls to observe the model. It should provide encapsulation and abstraction, protecting data from accidental modification by the system/developer. And so, I began tinkering until I had a model. I created some uses for it, fine tuned it, added some more features, etc. It was an object factory that returned a new model instance without having to use the “new” keyword.

I was pretty happy that ChocolateChip-UI would now have a model, but that got me to thinking – maybe ChocolateChip-UI could use a controller module too. So I looked at how the competition was dealing with controller behavior. And, in the end, I decided to take a completely different approach. I was creating a framework for mobile apps. These have unique challenges because they are mobile. So decided to base this work around the concept of mediators. These sit in the middle of an app’s interactions, like this image:

mediator

I used ChocolateChip-UI pubsub methods as the basis for my mediator module. But mediators have a number of unique features. You can control how many times a mediator can run or when it can run. Then I went back to my model code and updated it so that a model would automatically notify the mediator layer that it had changed. Like the model, this was also an object factory reusing the same pattern.

So now I had a model-controller for ChocolateChip-UI. I had always thought of ChocolateChip-UI as just a view. But it was a very passive and disconnected view because it had nothing built into it to enable working with other MVC frameworks. This meant that to use these required various workaround. It was not optimal, but it worked. I started thinking that maybe I could create a view module in the same way that I had create the model and controller modules. My idea was to enable a more component like pattern. I popped out the template parser from ChocolateChip-UI and put it into a new object factory. The object that this created knew about an element that it was associated with. This would be the container for any template rendering. It would automatically parse the element’s child nodes to extract a template. Or you could define a template in the view’s initializer. And you could define events in the view. And finally, you could bind a view to a model.

In the background the code would generate a mediator that would listen for any changes to the bound model. When a change would occur, it would update the rendered view.

So, I now had a model view controller framework. They had no dependency on ChocolateChip-UI. At the moment they were running on top of jQuery. While I was creating these modules, I kept comparing functions to mechanical ones. So, when I was done I realized I had something totally different from ChocolateChip-UI. It was time for a name change. I thought about vehicle names, but in the end I settled on TruckJS because trucks are powerful, they can carry heavy loads. You can count on trucks.

I then though I’d give a shot at rewriting ChocolateChip using the new patterns I used for TruckJS. But I was going to do one important thing. The new DOM library would be identical in API to jQuery so developers wouldn’t have to learn anything new to use it. In the end I had a DOM library less than half the size of jQuery with 90% of the functionality. But instead of the old Ajax syntax, I used the new Fetch API for remove server interaction. And instead of jQuery’s deferred object implementation, I went with the ECMAScript 6 Promises API. Fetch uses ES6 promises, so this was a perfect fit.

Then I though about routing, so I built a router. Then I added in data formatting and form validation. After that I began porting the widgets over. I wound up rewriting every single widget, changing their behavior to return objects and enabling the form-based widget to work with the new form validation.

TruckJS is a standalone framework without any dependency on other libraries or frameworks. You do not need jQuery, etc. It provides everything you need to build mobile web apps. But, if you really want to use jQuery with Truck, you can. You just have to load jQuery first. When Truck detects jQuery, it switches to using it instead of its own DOM library. I’m not sure why anyone would want to use jQuery. Its bulky and slow on mobile devices. But there’s always those special guys who think something can’t be perfect unless jQuery is loaded.

I’ve put up a site, TruckJS.io, with lots of documentation. And it’s available on Github. If you like ChocolateChip-UI, I think you’re really going to like TruckJS. It gives you the same tradition of great layouts and widgets for creating cross platform mobile web apps.

 

ChocolateChip-UI 3.0.3 Supports jQuery

As of version 3.0.3, ChocolateChip-UI now supports jQuery 2.0.3. We tried earlier versions of 2.x, but there where performance issues that prevented us from offering it as an option. jQuery 2.0.3 has proven to be a good option for mobile Web apps as far as size and speed. As such, going forward we will be supporting jQuery with the latest version of ChocolateChip-UI.

This means you can use other frameworks or plugins with jQuery dependencies and still take advantage of the great features in ChocolateChip-UI for creating cross-platform Web apps for iOS 7, Android Jelly Bean and Windows Phone 8.

For more information about jQuery support in ChocolateChip-UI, please visit ChocolateChip-UI.com and read the documentation for jQuery Support.

iOS 5 Style Switch Control

Recreating the iOS 5 Switch Control with HTML5, CSS3 and a Bit of ECMAScript 5

The final result of this post will run in iOS 5, Safari 5.1, as well as the latest versions of Chrome, Firefox and Opera.

Previously I had created a version of the switch control in iOS. With the launch of iOS5 Apple complete updated the look of the switch control. They went with a rounded style, which they also did with most controls in their desktop operating system, Lion.

After playing around with the early betas of iOS 5, I came up with the following reproduction of the new switch control look using just HTML5, CSS3 and some JavaScript for the interactive part. Functionally the switch control is nothing more than a fancier way of presenting a checkbox. So, for our purposes we are going to use a checkbox. Except that we need a couple of tags to wrap the checkbox so we can make it look like the switch control. Fortunately the amount of wrapper is really minimal. If you examine the picture below, you will notice that the switch control really has only two parts: the oblong base and the circular thumb. In our case we need a third part: a checkbox input.

Switch Control

We’re going to make a minor tweak to this default look. You’ll notice that the version above is in English. Actually, only the English version has labels for “On” and “Off”, everyone else uses the international symbols instead. They look like this:

International version of Switch Control

If we ignore the “On/Off” parts and just look at the colored areas we can see that we’re only really dealing with a simple vertical gradient on the thumb and some inset box shadows on the switch control base. This makes our styling really easy. For the “On/Off” parts we don’t need extra markup. You’ll notice that they exist in relation to the switch control’s thumb. We can use CSS pseudo elements on the thumb to create them.

To recreate the iOS5 switch control all we need is the following markup:

	<div class="switch">
		<span class="thumb"></span>
		<input type="checkbox" />
	</div>

Without styling, this gives us a very normal checkbox:

Unstyled switch control

We know what the dimensions need to be by measuring the screenshots, so we can give the switch control base some styling:

	.switch {
		height: 28px;
		width: 77px;
		border: 1px solid #979797;
		border-radius: 20px;
		overflow: hidden;
	}

This will give us the following:

Switch control with rounded border

It looks kind of funny with the checkboxes. We don’t need to see them. We will be setting their checked state with JavaScript later on anyway. So for now we can hide them:

	.switch input[type=checkbox] {
		display: none;
	}

Now let’s add some color. How to re-create that gray shadow area? We’ll use a series of inset box shadows. Like gradients, you can define multiple box shadows on an element. These stack up like layers, the last one being the bottom-most and the first being the top-most. We need to create a sizable gray choke inside the switch base, so we’ll use a box shadow with four values instead of three to create that effect:

	box-shadow: inset 0 12px 3px 2px rgba(232, 232, 232, 0.5);

To this we’ll add a second inset box shadow to create a darker shadow along the top inside of the switch control:

	box-shadow: inset 0 1px 3px #BABABA, inset 0 12px 3px 2px rgba(232, 232, 232, 0.5);

Switch control with gray box shadow

Here’s the complete CSS definition for the switch control:

	.switch {
		height: 28px;
		width: 77px;
		border: 1px solid #979797;
		border-radius: 20px;
		margin-top: -5px;
		box-shadow: inset 0 1px 3px #BABABA, inset 0 12px 3px 2px rgba(232, 232, 232, 0.5);
		cursor: pointer;
		overflow: hidden;
	}

Now for a tricky part. This gray inset box shadow is for the off state. How do we implement the bluish on state? Well, first of all we need to decide how to represent the states in markup. We’ll do this by added a class of “on” to the switch control base. That means that the base will have a class of “switch on” for when it’s flipped on and just “switch” when it’s off. We can use a pseudo element on the switch base to create the blue state and position it in view or out of view based on the presence of the “on” class. Of course we’re going to need a little JavaScript to set and remove the “on” class when the user clicks. So, here’s the CSS for the on state. We create an empty text node and give it the height we need to match the base. We don’t give it a width just yet since that will get set when the switch has the “on” class. We give it a bluish background color and inset box shadow. The absolute positioning is so that when it’s show, it doesn’t push the thumb out of the switch but instead sits independently inside the switch.

	.switch::before {
		content: "";
		display: block;
		height: 28px;
		width: 0px;
		position: absolute;
		border-radius: 20px;
		box-shadow: inset 0 1px 2px #0063B7, inset 0 12px 3px 2px rgba(0, 127, 234, 0.5);
		background-color: #64B1F2;
	}

To show the “on” state we just need to give the blue pseudo element the same width as the base:

	.switch.on::before {
		width: 77px;
	}

If we add the “on” class to one of our switches, we can see how the on state looks:

	<div class="switch on">
		<span class="thumb"></span>
		
	</div>

Switch control with 'on' state

That’s all we need for the switch control’s base. Now let’s tackle the thumb. We’ll make the span a block element with dimensions, set its positioning to relative so we can give it a higher z-index than the other elements in the switch control, specifically, the blue on state pseudo element. Next up: border, box shadow and gradient, very straightforward. And finally, because we want to have the thumb slide back and forth when the switch is clicked, we need to enable a CSS transition and give it a default translate value. Note: you will need to add an appropriate vendor prefix for the gradient, transition and transform.

	.switch > .thumb {
		display: block;
		width: 26px;
		height: 26px;
		position: relative;
		top: 0;
		z-index: 3;
		border: solid 1px #919191;
		border-radius: 28px;
		box-shadow: inset 0 2px 1px white, inset 0 -2px 1px white;
		background-color: #CECECE;
		background-image: linear-gradient(top, #CECECE, #FBFBFB);
		transition: all 0.125s ease-in-out;
		transform: translate3d(0,0,0);
	}

This gives us the following:

Switch control with thumb

As you can see, all thumbs are in the same place. We need to define a translate value for their “On” state:

	.switch.on > .thumb {
		-webkit-transform: translate3d(49px,0,0);
		-o-transform: translateX(49px);
		-moz-transform: translateX(49px);
	}

Which gives us:

Switch control thumb in 'on' state

Now the only thing left is to create the “on/off” indicators. We’ll start with the “on” one. It’s really quite simple. a vertical stripe with a border around it. We’ll create a pseudo element that has an empty text node, style it and position it beside the thumb. Here’s the CSS:

	.switch > .thumb::before {
		content: "";
		display: block;
		height: 14px;
		width: 2px;
		background-color: white;
		box-shadow: 0px -1px 1px #666;
		border: none;
		position: absolute;
		top: 6px;
		left: -24px;
	}

Switch control with 'on' state indicator

And for the “off” indicator, we create a pseudo element with an empty text node styles as a circle positioned to the right of the thumb:

	.switch > .thumb::after {
		content: "";
		display: block;
		height: 10px;
		width: 10px;
		border-radius: 10px;
		border: solid 2px #777;
		position: absolute;
		right: -32px;
		top: 6px;
	}

Switch control with 'off' state indicator

Now we have a fully styled switch control with minimal markup. We just need to add some interactivity. For that we’ll have to write some JavaScript. Since this is a self-contained example, I’m going to use the very latest version of ECMAScript 5. This gives me an easy way to get DOM elements and toggle classes on elements. If you want to reuse this you’ll need to switch those parts out for whatever methods your chosen JavaScript library provides.

So, first up I’m going to wrap everything up in an anonymous function:

	(function() {
	
	})();

Next I need a convenience method to get a collection of nodes and turn it into an array so I can iterate over it. I use call slice method of the Array object and pass in the results of querySelectorAll. That will convert the node collection into an array:

	(function() {
		var $$ = function(selector) {
			return Array.prototype.slice.call(document.querySelectorAll(selector));
		}
	})();

Now I want to define an event that executes when the DOM is fully loaded:

	(function() {
		var $$ = function(selector) {
			return Array.prototype.slice.call(document.querySelectorAll(selector));
		}
		document.addEventListener("DOMContentLoaded", function() {
		
		}, false);
	})();

After getting an array of all switch controls in the document, we iterate through them with the **forEach** method and bind a click event listener. The listener will execute a function that toggles the class “on”. ECMAScript 5 introduces a new token collection for classes called classList. This has several useful functions: add, remove, contains and toggle. To accomplish these methods with straight JavaScript you would need to use regular expressions. Instead I can just use **Element.classList.toggle(“on”)** to add and remove the class when the user clicks:

	(function() {
		var $$ = function(selector) {
			return Array.prototype.slice.call(document.querySelectorAll(selector));
		}
		document.addEventListener("DOMContentLoaded", function() {
			$$(".switch").forEach(function(switchControl) {
				switchControl.addEventListener("click", function toggleSwitch() {
					switchControl.classList.toggle("on");
				}, false);
			});
		}, false);
	})();

With the above JavaScript in our document, when the user clicks a switch control, the class “on” will be added to or removed from the switch, causing its thumb to slide to the left or right accordingly. This handily takes care of our visual requirements for the functionality of the switch control. However, we do need to manage the checked state of the checkbox. The first thing we’ll do is make sure any switch controls that had the class “on” during page load have their checkboxes set to chekced. Since the checkbox is the last element in the switch control div, we can reference it that way:

	(function() {
		var $$ = function(selector) {
			return Array.prototype.slice.call(document.querySelectorAll(selector));
		}
		document.addEventListener("DOMContentLoaded", function() {
			if (switchControl.classList.contains("on")) {
				switchControl.lastElementChild.checked = true;
			}		
			$$(".switch").forEach(function(switchControl) {
				switchControl.addEventListener("click", function toggleSwitch() {
					switchControl.classList.toggle("on");
				}, false);
			});
		}, false);
	})();

Next we need to update a switch controls checkbox when the switch control itself is clicked. We just need to again get a reference to the checkbox and set its clicked state to the opposite of what it was when the user clicked:

	(function() {
		var $$ = function(selector) {
			return Array.prototype.slice.call(document.querySelectorAll(selector));
		}
		document.addEventListener("DOMContentLoaded", function() {
			var checkbox;
			if (switchControl.classList.contains("on")) {
				switchControl.lastElementChild.checked = true;
			}		
			$$(".switch").forEach(function(switchControl) {
				switchControl.addEventListener("click", function toggleSwitch() {
					checkbox = switchControl.lastElementChild;
					checkbox.checked = !checkbox.checked;
					switchControl.classList.toggle("on");
				}, false);
			});
		}, false);
	})();

And that’s all you need to make the switch controls work. The final example has some extra JavaScript to output some text when the user flips a switch on to show them working. For Safari, Chrome and Opera, I use innerText to set the text value, but Firefox uses textContent. So the code has to deal with those differences.

You can try the working example. If you want the code, just save that page to your desktop. Everything is self-contained in the page.

ChocolateChip-UI for Zepto

I’ve ported ChocolateChip-UI to the JavaScript micro framework Zepto. Created by Thomas Fuchs of Scriptaculous fame, Zepto is a small JavaScript library for mobile devices that replicates the functions of jQuery. If you use jQuery but want to do mobile development and are disappointed with jQuery mobile’s size and performance, Zepto may be your solution. Zepto has a very small footprint and performs well on mobile devices. But Zepto provides only the equivalent of jQuery itself. If you need something to help you get your interface and widgets together, ChocolateChip-UI with Zepto provides a complete solution.

Although Zepto’s methods are the same as jQuery’s, it is not a clone of jQuery. The way it works internally is quite different. Yet it literally only took me a few hours to port the jQuery version of ChocolateChip-UI to Zepto. One major difference is that Zepto’s data method stores strings on a node using HTML5’s data attribute, whereas jQuery’s data method uses a sophisticated caching system to store any kind of data. However, on mobile browsers, HTML5 offers local storage and client side database for data persistence so this isn’t that big of a limitation. It does require more work (coding) on your part to accomplish the same thing that jQuery’s data method provides.

Check out .

Performance and size-wise, ChocolateChip-UI with Zepto is equivalent to ChocolateChip-UI with ChocolateChip. So, it’s really just up to a matter of personal preferences. If you like the coding conventions that jQuery demands, then go with Zepto. If you’d prefer more freedom to use normal JavaScript and want to break out of the jQuery mold, go with ChocolateChip.

CSS Gradients are about to Graduate!

Finally all browser vendors are on the same page when it comes to gradients

The Webkit team introduced CSS gradients on April 14th, 2008. Shortly afterwards they presented it to the W3C for consideration as a recommendation. Sometime later, Mozilla decided to implement CSS gradients using the same notation the Webkit gradients, but with the -moz prefix. After some time, however, they decided to replace that notation with a simpler one. Ever since, to do CSS gradients on the Web you had to write gradients the Webkit way for Safari and Chrome, and the Mozilla way for Firefox. Well, now all browser vendors have agreed to implement the same spec. At this time you can write a single notation that is identical for Safari, Chrome, Firefox, Opera and IE10.

Since version 5.1, Safari has supported the newer notation. Opera beta running Presto 2.10.299 fully supports the linear and radial notation, although the developer site only mentions support for the linear notation. Firefox, of course, already supports this notation. And the latest beta of IE10 does as well. This means that at some point all browsers will support this notation. Well, sort of.

Recently somebody at the W3C has been thinking a little too much. As of January 2012 the document CSS Image Values and Replaced Content Module Level 3 now has a slightly different notation. Since this just showed up, there is no support for it in any browser. And, since it is a working draft, it could change at any time. So, at this time, I’m going to ignore what the document says and just cover what the latest browsers have agreed to support.

Because CSS gradients are still a draft proposal, all browser vendors use their respective prefixes with the notation. This is a good thing since the spec is in flux. They shouldn’t change their present implementation until the spec reaches recommendation status, in which case they can implement the final version of CSS gradients without their vendor prefixes.

  • Webkit: -webkit-
  • Mozilla: -moz-
  • Opera: -o-
  • Microsoft: -ms-

CSS gradients are rendered as a background image. That means that all of the properties of the CSS background module apply to CSS gradients. In other words, you can have multiple gradients on the same element and control their size and position as well, or use them as image masks. Also, whereas in the past you might have used a background color in conjunction with a background image, you can now use a background gradients as the backdrop for a background image, or you could have a transparent gradient layered over a background image. The ability to stack up gradients while controlling their size, position and repetition means you can create complex repeating patterns that would normally require a background image. The ability to define multiple background images results in a layered affect not unlike Adobe Photoshop’s layers. The new CSS filters module will increase the comparison with Photoshop further my providing many color filters, such as reverse, multiply, dodge, burn, darken, lighten, grayscale, etc. With JavaScript you could also manipulate the properties of your CSS gradients to produce a background pattern that morphs in real time.

Linear Gradients

The notation for linear gradients is quite simple and straightforward. First thing, you’ll be defining it as a background image on an element. CSS uses functions that create the gradient according to the arguments you provide. For linear gradients, the values you’ll need are as follows:

[<point (one value, two values or degrees)>]?, <color [stop]?>, <color [stop]?>

From the above definition we can see that all values are optional, except the start and end colors.

The first value (point) is optional. If no value is provided, it will default to drawing the gradient from top to bottom. You can use keywords for the position. These can be a single keyword or a combination of two. You can also use any valid degree values. The purpose of these point definitions is to define which direction the gradient flow towards. You also need to provide at least two colors. The first color will be where the gradient starts from, and the last color will be where the point indicates. So a gradient with yellow and blue and a point value of top will start at the bottom with yellow and end at the top with blue. Here re possible point values:

– top
– right
– bottom
– left
– top left
– top right
– bottom left
– bottom right
– 0deg
– 11deg
– 67deg
– 182deg
– -45deg
– -90deg

Colors can have optional stop values. If no stops are provided, the colors will blend equally from the first to the last.You can provide as many colors as you want to create the gradient, and you can vary their widths by providing stops. The value of the stops can use any valid CSS length identifier (px, pt, em, %, etc.). The position value is placed after the color. You can use any valid CSS colors, such as keywords (red, yellow, blue), or hex, hsl, rgb or rgba values. Regardless of what the stop position is for the last color, that color will continue filling the element the rest of the way.

background-image: linear-gradient(top, yellow 10px, red 80px);
background-image: linear-gradient(top right, orange, green 30%, yellow 70%);
background-image: linear-gradient(60deg, red, white, blue 50%);

Repeating Linear Gradients

Repeat linear gradients are easy to do. Actually, the same effect can be achieved with background size and background repeat properties, but it is nice to have it I suppose. It works the same way as regular linear gradients, except that you use repeating-linear-gradient as the function:

background-image: repeating-linear-gradient(top, yellow 10px, red 80px);
background-image: repeating-linear-gradient(top right, orange, green 30%, yellow 70%);
background-image: repeating-linear-gradient(60deg, red, white, blue 50%);

Radial Gradients

The notation for radial gradients is similar to linear gradients, except that you can specific a shape argument to control how the radial is produced. Here’s the possible values:

[<position (two separate values)>]?[[<shape (literal value or length value)>] || [<size length value>]>]? <color [stop]?> <color [stop]?> 

From the above definition we can see that all values are optional, except the start and end colors, just like linear gradients.

If no value for position is supplied, the radial gradient will be centered in the element. Position is based on the center of the radial gradient. It accepts the same values as background position. Those values include percentages, lengths and keywords. Just like background positioning, you can use negative values to move the center of the radial gradient off the screen. Percentages and lengths require two values, the first defining the x axis and the second defining the y axis.

percentage: 0% 0%, 20% 60%, 50% 50%
length: 0px 0px, 24px 45px, 3em 5em

The keywords are: top, right, bottom, left and center. You could combine these in various ways:

top left, bottom right, center center, center right, top center

Shape can be either circle or ellipse. If no shape is supplied, if the length value is single, it defaults to a circle with a radius defined by that length. Otherwise, if no shape is supplied and two lengths are passed, it uses those to draw an ellipse. The first value determines the width, the second the height:

// A vertical ellipse:
background-image: radial-gradient(center, 100px 400px, red, white);
// An horizontal ellipse:
background-image: radial-gradient(center, 400px 100px, red, white); 

If you use one of the shape keywords, you can also use size keywords to control how the radial gradient is draw in relation to its container. The size keywords are:

– closest-side
– farthest-side
– closest-corner
– farthest-corner

First of all, these keywords only work when you use a shape keyword. Defining the shape of the radial gradient with lengths and then trying to use these size keywords will not work. So, this is how these size keywords work. If the container is narrower than it is tall, the size of circle or ellipse will be restrained by the left and right of the container. With farthest-side, it would be restrained by the top and bottom of the container, probably resulting in the left and right extending beyond those sides. Be aware that these work in relation to the position of the radial gradient. That means that if it is positioned near the top left, it will be rendered differently than if it were centered. Closest-corner and farthest-corner work just like closes-side and farthest-side. The best way to get the hang of these keywords is to play around with a radial gradient to see how they affect it. Although these keywords are nice conveniences, you’ll see that they are far from exact. If you need precise placement and size, you’re better off using lengths to define the size of your radial gradient.

Color and stops work similar to linear gradients. The first color defined the color drawn from the center of the radial gradient. The last color will define the outermost color of the gradient. Stops allow you to define more precise positioning of those colors in the radial gradient.

Repeating Radial Gradients

Like repeating linear gradients, it is possible to create the same effect as a repeating radial gradient. You’d just need to define it tediously repeating the colors and providing appropriate stops. In contrast, using the repeating-radial-gradient function makes this easy.

Practical Examples

Enough with theory. Let’s look at what we can do with linear and radial gradients. By layering them and controlling their size and positioning, we can create complex patterns that we can use as Web assets. Please note that in all of the following examples I’m presenting the gradients without vendor prefixes. To have them render in a browser that currently supports CSS gradients, you would need to provide the appropriate vendor prefix for that browser. When the current spec reaches recommendation status, browser vendors will drop their prefix.

In most of these examples I’ve used a transparent gray. This was so I could just add an background color to show through the transparency. Having the color controlled by the background color makes it easy to change the feel of the pattern.

Here’s a vertical stripe with the transparent gray stripe is separated by a 1 pixel transparent stripe:

background-image: 
   linear-gradient(0deg, 
      rgba(0,0,0,0.1) 75%, 
      transparent 75%);
background-size: 5px 100%;

vertical stripes gradient

Here’s the same stripe horizontal:

background-image: 
   linear-gradient(90deg, 
      rgba(0,0,0,0.1) 75%, 
      transparent 75%);
background-size: 100% 5px;

horizontal stripes gradient

And here it is slanted to the left:

background-image: 
   linear-gradient(45deg, 
      transparent 15%,  
      rgba(0,0,0,0.1) 15%, 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent 65%,
      rgba(0,0,0,0.1) 69%);
background-size: 6px 6px;

gradient of stripes slanting left

And then to the right:

background-image: 
   linear-gradient(-45deg, 
      transparent 15%,  
      rgba(0,0,0,0.1) 15%, 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent 65%,
      rgba(0,0,0,0.1) 65%);
background-size: 6px 6px;

gradient of stripes slanting right

Now lets have some fun with repeating linear gradients. Here’s vertical repeating stripes:

background-image: 
   repeating-linear-gradient(0deg, 
      rgba(0,0,0,0.1) 0px, 
      rgba(0,0,0,0.1) 5px, 
      transparent 5px, 
      transparent 10px);

repeating vertical stripes gradient

Horizontal repeating stripes:

background-image: 
   repeating-linear-gradient(90deg, 
      rgba(0,0,0,0.1) 0px, 
      rgba(0,0,0,0.1) 5px, 
      transparent 5px, 
      transparent 10px);

repeating horizontal stripes gradient

Left slanted repeating stripes:

background-image: 
   repeating-linear-gradient(45deg,
      rgba(0,0,0,0.1) 0px, 
      rgba(0,0,0,0.1) 5px, 
      transparent 5px, 
      transparent 10px);

repeating gradient of left leaning stripes

Right slanted repeating stripes:

background-image: 
   repeating-linear-gradient(-45deg,
      transparent, 
      transparent 5px, 
      rgba(0, 0, 0, 0.1) 5px, 
      rgba(0, 0, 0, 0.1) 10px);

repeating gradient of right leaning stripes

Now lets cross them:

background-image: 
   repeating-linear-gradient(0deg, 
      transparent 0,
      transparent 5px, 
      rgba(0, 0, 0, .1) 5px, 
      rgba(0, 0, 0, .1) 10px),
   repeating-linear-gradient(90deg, 
      transparent 0,
      transparent 5px, 
      rgba(0, 0, 0, .1) 5px, 
      rgba(0, 0, 0, .1) 10px);

checkered

And now criss-cross them:

background-image: 
   repeating-linear-gradient(-45deg,
      transparent, 
      transparent 5px, 
      rgba(0, 0, 0, 0.1) 5px, 
      rgba(0, 0, 0, 0.1) 10px),
   repeating-linear-gradient(45deg,
      transparent, 
      transparent 5px, 
      rgba(0, 0, 0, 0.1) 5px, 
      rgba(0, 0, 0, 0.1) 10px);

intersect

Enough with stripes, let’s get square:

background-image: 
   linear-gradient(180deg, 
      rgba(0,0,0,0.05) 75%, 
      transparent 75%),
   linear-gradient(90deg,  
      rgba(0,0,0,0.05) 75%, 
      transparent 75%);
background-size: 5px 100%, 100% 5px;

cubes

And a nice checkerboard pattern:

background-image: 
   linear-gradient(45deg, 
      rgba(0,0,0,0.1) 4.5px, 
      transparent 5px, 
      transparent 16px, 
      rgba(0,0,0,0.1) 16px, 
      rgba(0,0,0,0.1)), 
   linear-gradient(45deg, 
      rgba(0,0,0,0.1) 4.5px, 
      transparent 5px, 
      transparent 16px, 
      rgba(0,0,0,0.1) 16px, 
      rgba(0,0,0,0.1));
background-position: 0 0, 8px 8px;

squares

And let’s make those diagonal:

background-image: 
   linear-gradient(45deg, 
      rgba(0,0,0,0.1) 25%, 
      transparent 25%),
   linear-gradient(-45deg, 
      rgba(0,0,0,0.1) 25%, 
      transparent 25%),
   linear-gradient(45deg, 
      transparent 75%, 
      rgba(0,0,0,0.1) 75%),
   linear-gradient(-45deg, 
      transparent 75%, 
      rgba(0,0,0,0.1) 75%);
background-size: 10px 10px;

chess

Now that we have them diagonal, lets spice them up and turn them into an argyle pattern:

background-image: 
   linear-gradient(right top, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent),
   linear-gradient(left top, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent);
background-size: 12px 12px;

argyle

OK, now lets take another look at stripes. But this time we want to shake things up about. We want to get out to the monotony of strictly repeating patterns, but still have a pattern. What I’m talking about is sometimes called the Cicada principle. It produces a pattern that doesn’t repeat itself exactly. It does this my layering different repeating patterns, except that these are different proportions, similar to the progression of prime numbers. Using this principle, I’ve created a series of overlapping lines that creates a textile like pattern that retains it’s randomness. Here’s the CSS:

background-image: 
   linear-gradient(left, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 25%, 
      transparent 25%, 
      transparent),
   linear-gradient(left, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 15%, 
      transparent 15%, 
      transparent),
   linear-gradient(left, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 15%, 
      transparent 15%, 
      transparent),
   linear-gradient(top, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 17%, 
      transparent 17%, 
      transparent),
   linear-gradient(top,
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 15%, 
      transparent 15%, 
      transparent),
   linear-gradient(top,
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 13%, 
      transparent 13%, 
      transparent);
background-size: 10px 100%, 17px 100%, 21px 100%, 100% 10px, 100% 17px, 100% 21px;
backgroud-position: 0 0, 6px 0, 14px 0, 0 0, 0 6px, 0 16px;

linen

Now lets play with radial gradients. We’ll start with basic patterns and build up to more complex combinations.

background-image:
   radial-gradient( 
      rgba(0,0,0,0.1),
      rgba(0,0,0,0.1) 45%,
      rgba(0,0,0,0) 50%,
      rgba(0,0,0,0) 95%);
background-size: 8px 8px;

speckeled

Now we’ll take the above pattern and turn the dots inside out so that the pattern looks like someone cut holes in the color.

background-image:
   radial-gradient( 
      rgba(0,0,0,0),
      rgba(0,0,0,0) 50%,
      rgba(0,0,0,0.1) 55%,
      rgba(0,0,0,0.1) 95%);
background-size: 10px 10px;

spotted

Now we’ll just play with the size of circles a bit.

background-image:
   radial-gradient( 
      rgba(0,0,0,0.1),
      rgba(0,0,0,0.1) 9px,
      rgba(0,0,0,0) 9px,
      rgba(0,0,0,0) 17px);
background-size: 18px 18px;

circles

OK, I now the above patterns are not revolutionary or anthing. Now we’re going to get creative. For the next ones we’re going to user colors, yeah! The next pattern has a gold background with orange and greenish polka dots:

background-image:
   radial-gradient( 
      rgba(255,0,0,0.2),
      rgba(255,0,0,0.2) 4px,
      rgba(255,255,255,.10) 5px,
      rgba(255,255,255,.10) 7px),
   radial-gradient( 
      rgba(0,0,0,0.2),
      rgba(0,0,0,0.2) 4px,
      rgba(255,255,255,.25) 5px,
      rgba(255,255,255,.25) 7px);
background-size: 18px 18px;
background-color: #ffd239;
background-position: 10px 10px, 0% 0%;

gold-polka-dots

The next one I call puff balls because of their look:

background-image:
   radial-gradient(
      rgba(255,255,255,0) 90%,
      rgba(255,255,255,.5) 90%,
      rgba(255,255,255,.5)
   ),
   radial-gradient( 
      rgba(255,255,255,0.01),
      rgba(255,255,255,0.01) 10%,
      rgba(255,255,255,255.1) 70%,
      rgba(0,0,0,0) 79%,
      rgba(0,0,0,0) 96%);
background-size: 20px 20px;
background-color: #ff77a1;

puff-balls

Here’s another gold pattern with four-pointed stars:

background-image:
   radial-gradient( 
      rgba(255,0,0,0.2),
      rgba(255,0,0,0.2) 8.5px,
      rgba(255,255,255,.5) 9.5px,
      rgba(255,255,255,.5) 17.5px),
   radial-gradient( 
      rgba(0,0,0,0.2),
      rgba(0,0,0,0.2) 8.5px,
      rgba(255,255,255,.15) 9.5px,
      rgba(255,255,255,.15) 17.5px);
background-size: 18px 18px;
background-color: gold;
background-position: 9px 9px, 0% 0%;

gold stars

And here we change the background to green:

background-image:
   radial-gradient( 
      rgba(255,210,57,0.42),
      rgba(255,210,57,0.42) 9px,
      rgba(0,0,0,0) 11px,
      rgba(0,0,0,0) 15px),
   radial-gradient( 
      rgba(0,0,0,0),
      rgba(0,0,0,0) 9px,
      rgba(255,210,57,1) 10px,
      rgba(255,210,57,1) 15px);
background-size: 17px 17px;
background-color: #1e8e04;
background-position: 8.5px 8.5px, 0% 0%;

green stars

And finally, we do some interesting overlap with the radial gradients:

background-image:
   radial-gradient( 
      rgba(255,255,255,0),
      rgba(255,255,255,0.5) 14px,
      rgba(255,255,255,0) 14px,
      rgba(255,255,255,0) 26px),
   radial-gradient( 
      rgba(0,0,255,0.31),
      rgba(0,0,255,0.31) 14px,
      rgba(255,255,255,0) 16px);
background-size: 28px 28px, 28px 28px;
background-position: 14px 18px, 0% 18px, 0% 0%;
background-color: rgba(200,250,190,0.5);

petals

You can see these gradients in action here. You can same the page to your desktop, since it is a self-contained document.

Proposed Changes to Spec

So, as I mentioned, since January 2012 the draft for CSS gradients at the W3C has some notation changes. Really their minor, but in my opinion, not necessary. Actually, I’m irritated by them. The two owners of the document: Elika J. Etemad and Tab Atkins Jr., from Mozilla and Google respectively, have decided to make the notation more English-like by requiring prepositions for the position keywords for linear and radial gradients. So if you had a yellow to red linear gradient that ended in the bottom right, you’d need to write the following:

linear-gradient(to bottom right, yellow, red);

For a radial gradient, it would be

radial-gradient(circle at closest-side, yellow, red);

OK, so if the point is to make it more English-like, shouldn’t it be:

linear-gradient(to the bottom right, yellow, red)

Or better yet:

linear-gradient(directed toward the bottom right, yellow, red);

Or:

radial-gradient(a circle positioned at closest-side, yellow, red);

And, last time I check, a big chuck of the world doesn’t know what the English word “to” means and so it adds no clarity to what the keywords are doing. I’m totally against requiring unnecessary English grammatical constructs in to CSS. We don’t do that with HTML or JavaScript. What strikes me as really odd, one of the authors is from Mozilla. They were the guys that complained that the original Webkit notation used “to” and “from” to designate the start and end colors. Now they want to make the simpler notation more complicated. Adding prepositions to keywords for gradients will not add any new functionality nor prevent any rendering errors. They just make the notation more wordy. Fail! Making CSS more English-like is a rabbit hole down which you do not want to go.

March 23, 2012

Since writing this post there has been some ongoing discussion at CSS Working Group about the reasoning behind the use of prefixes in the new syntax. The gist of it is that prepositions actually remove the ambiguity of direction when dealing with gradients. Here’s a quote from the discussions:

The “to” keyword was added to linear gradients because there was
significant confusion about whether “top” meant “start from the top
(put the 0% color on the top)” or “point toward the top (put the 100%
color on the top)”.

Radial gradients gained keywords in an attempt to make the syntax more
flexible and more readable – previously, for example, you could have a
declaration like “radial-gradient(20% 20%, 30% 30%, black, white)”.
It’s very unclear what that means – even if you know that one of them
is a position and the other is a size, how can you tell which is
which? Due to this ambiguity, the syntax also disallowed specifying
just a size without a position.

The new syntax, while not ideal in some ways, solves this problem –
you’d write the previous example as “radial-gradient(30% 30% at 20%
20%, black, white)” which gives you some clues as to which is the size
and which is the position. As well, it’s now possible to specify
either a size or a position alone, and have it parsed unambiguously –
“radial-gradient(30% 30%, black, white)” has an explicit size and
default position, while “radial-gradient(at 20% 20%, black, white)”
has an explicit position and default size.

In light of the above I’ve been won over to support prepositions in the gradient syntax. It solves the problems described above and will make creating gradients easier for everyone.

Back and Next Buttons Revisited

So, many moons ago, I wrote a post about how to make iOS style “Back” and “Next” buttons using CSS. Only problem was that technique used a span tag to create the pointer. For some reason it slipped my mind that I could use the CSS generated content property with the :before pseudo-element. Rather than being bothered with having to stick spans into buttons to turn them into pointers, I now introduce you to a more sane method of creating “Back” and “Next” buttons with just CSS.

Now you might be wondering how we would generate the node we need to style as a pointer. Using the CSS content property we can generate automatic content inside the button, removing the necessity of having a tag sitting there for no other reason. Unfortunately the content property only generates alpha-numeric content. We can’t use it to create a span or any other tag. But we don’t have to use a normal character as the content. A space will suffice to create the desired pointer. We make it display as a block element and then style it as if it were a normal pointer. Problem solved.

To accomplish our goal we need to switch out any reference to < span.pointer for :before

So, here’s the styles for a normal button, followed by the styles for the pointer.


.button.bordered.back:before {
	content: " ";
	display: block;
	z-index: 0;
	background-image: 
		-webkit-gradient(linear, left top, right bottom, 
			from(#92a1bf), 
			color-stop(0.3, #798aad),
			color-stop(0.51, #6276a0), 
			color-stop(0.51, #556a97), 
			color-stop(0.75, #566c98),
			to(#546993)); 
	border-left: solid 1px #484e59;
	border-bottom: solid 1px #9aa5bb;
	-webkit-border-top-left-radius: 5px;
	-webkit-border-bottom-right-radius: 5px;
	-webkit-border-bottom-left-radius: 4px;
	height: 23.5px;
	width: 23.5px;
	display: inline-block;
	-webkit-transform: rotate(45deg);
	-webkit-mask-image: 
		-webkit-gradient(linear, left bottom, right top, 
			from(#000000), 
			color-stop(0.5,#000000), 
			color-stop(0.5, transparent), 
			to(transparent));
	position: absolute;
	left: -9px;
	top: 2.5px;
	-webkit-background-clip: content;
}
.button.bordered.back:hover:before, .button.bordered.back.touched:before {
	background-image: 
		-webkit-gradient(linear, left top, right bottom, 
			from(#7d88a5), 
			color-stop(0.3, #58698c),
			color-stop(0.51, #3a4e78), 
			color-stop(0.51, #253c6a), 
			color-stop(0.75, #273f6d),
			to(#273f6d)); 
}

You can check out the finished version online or download the source code.

ChocolateChip-UI

Learn more about ChocolateChip-UI

ChocolateChip.js is now ChUI (pronounced “chewy”)

In the course of time I’ve created a lot of POCs (proof of concepts) on this blog. Some where fairly good, some where flaky one-offs. In the process I also created a small JavaScript library — ChocolateChip.js — that I used for actualizing most of these demos. Seeing how many people come to this humble blog in search of solutions to their development projects, I though about taking all the good ideas in these demos and putting them together as a one stop solution for mobile Web app development. I’m therefore today announcing ChocolateChip-UI. At present it’s a beta, but I intend to keep developing it to add more useful features over time. I

ChocolateChip-UI consists of ChocolateChip.js plus two other files: ChUI.js and ChUI.css. ChUI.js is a collection of JavaScript methods built on top of ChocolateChip.js. ChUI.js provides controls and widgets enlivened with behaviors needed for Web app development. ChUI.css is the magical CSS that makes simple markup look and act in a amazing way.

ChocolateChip-UI also introduces a new concept: WAML (Web App Markup Language). This is a specialized set of tags and attributes that get around the limits of HTML. HTML tags are really about creating documents, like books and other text publications. In contrast, WAML is a collection of tags and attributes that make sense for Web app development. ChUI.js and ChUI.css are built around the implementation of WAML as the key to how ChocolateChip-UI works.

WAML takes the paradigms of mobile application development and transfers those over to the development of mobile Web apps. There’s no need to smother and bury HTML tags with tons of classes trying to make markup meant for publishing documents work for creating applications. At the same time, WAML is really just a superset of HTML5 markup. You can therefore use any HTML5 tags and attributes along with WAML and ChocolateChip-UI to implement your solution.

ChocolateChip-UI is about making Web app development more straightforward. It provides common controls which have built in functionalities. Instead of having to figure out how to build these yourself, you can spend that time providing the data you want through ChocolateChip-UI’s controls easy to use controls.

The interfaces and controls which ChocolateChip-UI provides are all created using only markup and CSS. No images are required, no gifs or pngs. This means that everything you build with ChocolateChip-UI will be resolution independent. It will look good on a handheld mobile device and on a big HDMI screen. ChocolateChip-UI also provides a set of 52 SVG icons for use with buttons. Because these are vector based, they too are resolution independent. ChocolateChip-UI is therefore the first resolution independent mobile Web app framework.