Reuse and Recycle: SVG

SVG has had a long and strange journey to the world of ‘emerging technologies” SVG was actually defined in 1999, so it’s not exactly the new kid on the block. Still, it took a while to catch on, so in some ways it feels like the new kid on the block. Like Canvas, SVG allows developer sot create graphics in the browser using native web technologies. Unlike Canvas SVG is a vector based grammar and, since it’s defined as XML it also allows for access using common DOM manipulation tools. One of the most difficult issues when dealing with Canvas is the need to manually manage the state, properties and events of individual elements. Since SVG elements are simple DOM elements, properties are stored as part of the regular DOM and access to individual elements is available using traditional DOM access methods like document.geElementById and document.getElementsByTagName.

One driver of popularity for SVG has been the emergence the RaphaelJS library. Raphael provides a convenient API on top of the specification and provides some measure of support for legacy IE browsers by rendering the output of Rapehl instructions as Vector Markup Language (VML.)

The following example shows Raphael and SVG in action. Example output can be seen in the following figure.
Created with Raphaël 2.1.0

The following code sample illustrates using Raphael to draw 10 random circles on an SVG element, filling them with a random gradient fill. The code is quite simple, with a new paper variable containing the instance of Raphael in use and then straightforward methods circle() and attr() used to create circles and fill them with the fancy gradient fill.

<!DOCTYPE html>
<html>
<head>
  <meta charset=UTF-8">
  <title>SVG</title>
</head>
 <style type='text/css'>
    #svg {
    width:100%;
    height:600px;
}
  </style>
</head>
<body>
  <div id="svg"></div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js'></script>
  <script src='demo.js'></script>

</body>
</html>
window.onload=function(){
var svg = document.getElementById("svg"),
    paper = Raphael( svg ),
    circle,
    width = svg.offsetWidth,
    height = svg.offsetHeight;

for (var i = 0; i < 10; i++) {
  circle = paper.circle(
    parseInt(Math.random() * width), 
    parseInt(Math.random() * height ), 
    parseInt(Math.random() * 200));
  circle.attr({
    "fill": "r" + hex() + "-" + hex(),
    "fill-opacity": "0.5",
    "stroke": "none"
  });
  circle.click(function() {
    console.log(this);
    this.animate({
      cx: parseInt(Math.random() * width),
      cy: parseInt(Math.random() * height),
      r: parseInt(Math.random() * 200)
    }, 1000, "bounce")
  });
}

function hex() {
  //http://paulirish.com/2009/random-hex-color-code-snippets/
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
  }
}

Inspecting the output the underlying markup isn’t quite so succinct, although it should be readable if you’re familiar with XML syntax and can follow along with the code that generated the example. The following code sample shows a single circle marked up using SVG syntax.
The interesting pieces to note are the definition of the radialGradient in the defs element. defs are used for reusable content. You can see it referred to in the circle element’s fill url.

<svg height="400" version="1.1" width="400" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: absolute; left: 0px; top: 0px;">
  <desc>Created with Raphaël 2.1.0</desc>
  <defs>
    <radialGradient id="0r_7d7f2f-_bbb372" fx="0.5" fy="0.5">
      <stop offset="0%" stop-color="#7d7f2f"/>
      <stop offset="100%" stop-color="#bbb372" stop-opacity="0.5"/>
    </radialGradient>
  </defs>
  <circle cx="170" cy="68" r="61" 
          fill="url(#0r_7d7f2f-_bbb372)" 
          stroke="none" 
          style="opacity: 1; fill-opacity: 1;" 
          opacity="1" fill-opacity="1"/>
</svg>

Reuse and Recycle: The Canvas 2D API

The canvas element and associated API started life as an Apple extension to HTML. From there it blossomed into one of the early stars of the HTML5 era. The canvas element provides a scriptable interface for drawing two-dimensional images in the browser. Even without full browser support on the desktop, developers have embraced canvas fully. It’s been used for everything from high traffic visualizations to game engines, a popular system for delivering custom fonts, and a port of the Processing programming language into JavaScript.

While the true power of the Canvas 2d API is beyond the scope of this higher level introduction, it’s worth looking at the API in brief, if just to get a flavor for what it looks like. The following code sample shows a small canvas element and associated JavaScript that draws out a tic-tac-toe game. The simplest piece is the canvas element itself. A canvas element operates much like any other replaced element like a video tag or an image. The big difference is that it lacks a src attribute. The “src” of the canvas image is provided by JavaScript.

<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="_assets/css/style.css">
</head>
<body>
<header>
  <h1>Mobile Web App Cookbook, Canvas</h1>
</header>
<canvas id="ctx" height="300" width="300"></canvas>
<footer>
  <p>&copy; <a href="https://htmlcssjs.wpengine.com/" rel="me">Rob Larsen</a></p>
</footer>
<script src="_assets/js/libs/jquery-1.7.1.min.js"></script>
<script>
//canvas script follows below
</script>

</body>
</html>

The Canvas API is illustrated the in the following script block. It starts by getting a reference to the context of the canvas element. The context is where information about the current rendering state of the element is stored. It contains both the pixel level state of the image as well as various properties and access to core canvas methods used to further manipulate the image. After that you’ll see a variety of basic drawing commends. A path is created using the ctx.beginPath() method and then several context level styles are set. Following that a simple for loop is used to draw lines at regular intervals on the screen. The combination of moving the insertion x/y point of the drawing using ctx.moveTo and drawing the actual line using ctx.lineTo is enough to illustrate the familiar tic-tac-toe board. Following that the “game” is played using a series of text insertions, alternating different fillStyle colors between “turns.”

$( document ).ready(function(){
  var ctx = document.getElementById( "ctx" ).getContext( "2d" ),
  width =  document.getElementById( "ctx" ).width;
  //draw the board
  ctx.beginPath();
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 4;
  for ( var i=1; i < 3; i++ ){   
    ctx.moveTo( ( width / 3 ) * i, 0 );
    ctx.lineTo( ( width / 3 ) * i , width );
    ctx.moveTo( 0, ( width / 3 ) * i );
    ctx.lineTo( width, ( width / 3 ) * i );
  }
  ctx.stroke();
  ctx.closePath(); 
  //"play" the game in order
  ctx.font="80px Arial, Helvetica, sans-serif";
  ctx.fillStyle="#c00";
  ctx.fillText( "x", 130, 170 );
  ctx.fillStyle="#000";
  ctx.fillText( "0", 30, 70 );
  ctx.fillStyle="#c00";
  ctx.fillText( "x", 30, 170 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 230, 170 )
  ctx.fillStyle="#c00";;
  ctx.fillText( "x", 130, 70 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 130, 270 );
  ctx.fillStyle="#c00";
  ctx.fillText("x", 230, 70 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 30, 270 )
  ctx.fillStyle="#c00";;
  ctx.fillText( "x", 230, 270 );
});

This is a simplistic example but it should illustrate the flavor of the API and, hopefully, will get you excited to use some more advanced features.

Reuse and Recycle: A Quick Intro to Microdata

Microdata

HTML5 defines a standardized scheme for marking up and retrieving metadata in the body of an HTML document. If you’ve worked with microformats like hCard and hCalendar then microdata will be relatively familiar. The biggest change is the move from the class name hijacking central to microformats to a new itemprop attribute. In addition to this designed solution Microdata adss two new attributes and one dom method that provides standard access to microdata. itemscope sets the scope of a microdata segment, itemtype defines a URL for the microdata format in use and document.getItems() provides access to microdata. The method returns a NodeList containing the items corresponding to an optional itemType argument or all types, if no argument is provided. the following code listing shows a sample document that features a simple bio of your humble author marked up with microdata. It leverages microdata formats from schema.org and mixes and matches three separate microdata formats, Person, Postal Address and Organization.

<!doctype html>
<html class="no-js" lang="en">
<head>
  <meta charset="utf-8">
  <title>Microdata  Example</title>
  <link rel="stylesheet"  href="_assets/css/style.css">
  <script src="_assets/js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body id="microdata">
  <div  id="main">
    <div itemscope  itemtype="http://schema.org/Person">
      <h1  itemprop="name">Rob Larsen</h1>
      <img  src="http://gravatar.com/avatar/88218052898935c38927c1a5e607c794?size=420"  itemprop="image" />
      <h2  itemprop="jobTitle">Senior Specialist, 
        <span  itemprop="worksFor"><span itemprop="name" itsemscope  itemtype="http://schema.org/Organization">
        Sapient Global  Markets</span></span></h2>
      <ul itemprop="address" itemscope  itemtype="http://schema.org/PostalAddress">
        <li  itemprop="streetAddress"> 131 Dartmouth St. </li>
        <li><span  itemprop="addressLocality">Boston</span> <span  itemprop="addressRegion">MA</span></li>
        <li>Rob's email: <a  href="mailto:jane-doe@xyz.edu" itemprop="email">  rob@htmlcssjavascript.com</a> </li>
        <li>Rob's  Blog: <a href="https://htmlcssjs.wpengine.com/"  itemprop="url">htmlcssjavascript.com</a> </li>
        <li><a  href="http://twitter.com/robreact/"  itemprop="url">@robreact on Twitter </a> </li>
        <li><a  href="https://github.com/roblarsen"  itemprop="url">roblarsen on github</a> </li>
      </ul>
    </div>
  </div>
  <script src="code.jquery.com/jquery-1.7.1.min.js"></script>
</body>
</html>

Reuse and Recycle: The History API

The new history API helps to solve one of the most troubling usability issues with Ajax application development (and Flash before it.) By default, if you use the back button on a single page app, you navigate away from the page in question. The expected behavior is to travel back to the previous state of the application.

This can mean potentially losing dozens or even hundreds of historical interactions.

While it’s true that there are script-based solutions available now to handle dynamic state in an Ajax application, the new HTML5 history API provides a single, standard solution. There’s no more choosing between schemes.

It’s not magical. In fact it leaves quite a bit of work to do. You still have to manage and reacreate application state, storing application data in a series of JavaScript objects that populate the history stack.

The following code sample illustrates a basic example. In this simple page a button click changes the color of the page background. Every time this button is pressed the history.pushState method is called. It accepts three arguments, an object representing the history state, a title for the state and a new URL to display in the browser.  The state is the most important argument. In this case it’s simply an object with one property color whose value is the new hex value of the page background. It should represent whatever info you need to recreate that state in the history stack.

To do that, you need to bind a function to the popostate event. This function process the same state passed into history.pushState. In this simple example it just reads the color property but it could do anything needed to rebuild application state. In this example we’re accessing the data in e.originalEvent because of the way that jQuery handles events. The abstraction/compatibility layer on top of the standard event handling buries the original event data one layer down. If you were binding events with window.addEventListener you could skip e = e.originalEvent.

<!doctype html>
<html>
<head>
  <meta  charset="utf-8">
  <title>History Example</title>
</head>
<body>
  <div id="main">
    <button  id="historymaker">click to add to the history stack</button>
    <p  id="reporter">The Background color is #ffffff</p> 
  </div>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script>
    $( document  ).ready(function(){
      $(  "#historymaker" ).on( "click" , function(){
        //http://paulirish.com/2009/random-hex-color-code-snippets
        var color  = '#'+Math.floor( Math.random()*16777215  ).toString( 16 ) ;
        $( "body"  ).css( { "background-color" : color } );
        $(  "#reporter" ).text( "The background color is " + color );
        history.pushState(  { "color" : color }, color, color.slice( 1 , color.length  )+".html" ); 
      })

      $( window ).on(  "popstate" , function( e ){
        e = e.originalEvent;
        if ( e.state !== null  ){
          $( "body"  ).css( { "background-color" : e.state.color } ); 
          $(  "#reporter" ).text( "The background color is " +  e.state.color);
        } else {
          $( "body"  ).css( { "background-color" : "#fff" } );
          $(  "#reporter" ).text( "The background color is #ffffff" );
        }
      });

   });
</script>
</body>
</html>

Reuse and Recycle: New Form Elements, Attributes and Input Types

This article is available in Serbian/Srpski

In addition to the new semantic elements HTML5 provides several major enhancements to the way forms are handled. New elements, input types and attributes have been added to better map common web inputs.

For example, common web text formats like Email and URL can now be indicated to the browser in a meaningful way using new input types.  Mobile devices are leading the way in implementing novel UI enhancements based on to these new form elements. Visit a site with an input type="email" on an iOs device and you’ll see the following special on-screen keyboard.

Image illustrating the special keyboard present in iOs for email inputs. check out the @ symbol.

Image from Dive Into HTML5

What’s especially nice about these new form inputs is that they’re completely backwards compatible as all browsers treat unknown form types as type="text."

Some of the new form attributes are very handy and will, eventually replace a mountain of JavaScript in the wild. Attributes like placeholder, for default text in a form input, autofocus, designed to indicate which form element should receive focus when a page is visited and required, which indicates a field in a form that must contain a value for the form to be submitted, all represent common form tasks on the web that are currently handled by JavaScript. With well-written fallback code these form attributes are safe to use as older browsers just ignore the unknown attributes.

The support outlook for the completely new form elements and input types isn’t so rosy. Polyfill solutions exist, but the whole point of looking at input type="color", for a color picker, or the new meter, which indicates usage, and progress, which indicates the progress through a task,  elements is to get away from using complicated JavaScript for this common functionality. Unlike something like the placeholder attribute, which can be rewritten in just a few lines of pure JavaScript, something like a color picker or progress indicator relies on a combination of CSS, HTML, JavaScript and associated images. The benefit of having native controls would therefore be significant.

The following code sample illustrates a few of these new form enhancements in action.  First is a meter created with a scale of 0 to 25 with an initial value of 10, then there’s a progress element set to 42/100 and finally there are examples of two of the new input types. Both take advantage of the required attribute and the email has a placeholder. As you can see they’re all very simply designed, so with proper support from browsers they’ll offer significant UI enhancements to web applications with very little code overhead.

 <header>
    <h1>Forms, Forms, Forms</h1>
 </header>
<div id="forms">
    <label>Meter:    
       <meter min='0' max='25'  value='10'></meter>
    </label>
    <label>Progress: 
        <progress max='100'  value='42'></progress>
    </label>
    <input  type="email" required placeholder="email@example.org" >
    <input  type="url" required >
</div>
What the previous code sample looks like in a compliant browser.

Forms aren’t the sexiest area of HTML5 to demo, so people sometimes ignore them. I think they;’re pretty important.

People make money on the web by getting people to enter information into forms. Forms pay the bills. Anything that makes forms better is going to make the web a better place.

Take some time and look at the full suite of form enhancements. They’re pretty slick.