Home Web Development HTML5 for Flash Developers

HTML5 for Flash Developers

By Matthew Fisher
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Why HTML5?
About this book
As the support for HTML5 within modern web browsers grows, the appeal of HTML5 development, especially for Flash developers, is at an all-time high. From 3D interactive multi-user content to high definition video streaming, HTML5 can deliver it all, to almost all modern web browsers, desktops, and mobile platforms. HTML5 for Flash Developers is a practical, targeted guide for developers with previous experience in developing applications in Flash who would like to add HTML5 development to their skill set. By understanding key aspects that make HTML5 development different from Flash you will be able to integrate your current skill set into the HTML5 development paradigm. Starting with identifying the key technologies that make up the HTML5 development stack and how they are utilized to create HTML5 content, HTML5 for Flash Developers will cover the traditional HTML5 application development flow chapter by chapter, while covering many other common tools that are regularly used in HTML5 today.In addition to understanding and writing dependency-free HTML5 code, you will also learn how to build your HTML5 applications on top of popular libraries and frameworks such as jQuery and CreateJS. This book covers how to prepare all of your content and media for integration into your HTML5 application using applications such as the Miro Video Converter or Adobe Photoshop. You will learn ways to not only continue to use Adobe Flash in your HTML5 application content preparation flow, but also how to port your existing Flash content right over to HTML5.Once you understand what it takes to build HTML5 content, you will finish up by learning how to debug, optimize, and prepare your content for release on the Web.
Publication date:
July 2013
Publisher
Packt
Pages
322
ISBN
9781849693325

 

Chapter 1. Why HTML5?

Before getting started, it is important that you understand what HTML5 is, how it works, and how it relates to what you already know as a Flash developer. This book uses Adobe Flash (CS6) as a reference when comparing functionalities of HTML5 with what Flash developers are commonly used to while creating applications in Flash. Therefore, a solid understanding of both the Adobe Flash IDE as well as ActionScript 3 will be required to properly follow the examples within this book.

In this chapter you will learn:

  • What HTML5 actually is and what technologies are included within it

  • Reasons for adding HTML5 development to your skillset

  • Avoiding the initial issues involved in transitioning from Flash development

  • Modern browser compatibility with HTML5 functionality

 

Understanding HTML5


As a Flash developer, you have probably worked with HTML on a frequent, if not daily, basis as a platform for publishing your compiled Adobe Flash SWF files on the Web. Although web browsers with Flash Player installed can view standalone SWF files, it is normal practice to embed Flash content within an HTML document. Thanks to the simplistic syntax and availability of HTML, many people who are not even developers have learned traditional HTML development techniques. Unfortunately, early HTML specifications fell short in many areas of displaying content online. Common tasks such as creating rich interactive experiences, sharing multimedia assets, or creating web-based user interfaces to act in a more typical software-like manner became a massive chore, if not impossible. In the recent past, Flash has been the obvious choice when developing and integrating assets such as video and audio playbacks, web-based games, 3D interactive graphics, and inline advertisements. Lately, many of these features on the Web have been remade using HTML5 allowing users to access the content in the same manner, but without the use of technology such as Adobe Flash Player.

The ability to build quality web-based content that can be globally accessible from any device is the key to a successful product or service. Facebook, Google, and Twitter are all using HTML5 to better the user experience of their applications and deliver content to users without the need for third-party plugins. More businesses are saving time, resources, and money during their application development process by utilizing the HTML5 development stack to target not only web browsers on desktop and mobile, but also installable applications on both platforms as well.

Transitioning your Flash development skills to HTML5 is a fun process that will not only open you to more opportunity professionally, but enable you to better analyze what tool is right for the job at hand. Adobe Flash isn't going anywhere anytime soon, but the same can easily be said for HTML5.

Since many developers flock to Flash development from previous web and application development technologies that may have had nothing to do with HTML, let's start by covering the essentials of the HTML5 stack.

What is HTML5?

HTML5 is the fifth and latest version of the HTML standard developed by the World Wide Web Consortium (http://www.w3.org/). Being a new version, it brought some new features to the existing HTML specification as well as removed some of the old outdated features. Many of these new and existing features are starting to closely resemble the feature set within Adobe Flash, thus opening many new facets of web development, which are not reliant on paid applications or browser plugins such as the Adobe Flash Player.

The development of the HTML5 specification is still a work in progress and is scheduled to be finalized and released sometime in 2014, but most of the modern web browsers today support many features of the specification already.

Generally, references to HTML5 refer to a suite of features and technologies surrounding the usage of not just HTML but Cascading Style Sheets (CSS) as well as JavaScript . Without the use of CSS and JavaScript, plain HTML documents, even HTML5 documents, will remain extremely simplistic in their functionality and look and feel. Therefore, learning HTML5 is effectively learning three technologies simultaneously. As tedious as that sounds, Adobe Flash is setup in a very similar way. The Flash IDE allows easy creation, editing, and referencing of assets to be used within your application. To integrate these assets into a dynamic interactive application requires the use of ActionScript. HTML5 is very similar to this such that HTML and CSS will be your Flash IDE and JavaScript will be the replacement for ActionScript. With all this in mind, let's continue by reviewing the standards on which HTML is built.

HTML standards

The World Wide Web Consortium (http://www.w3.org/) or W3C, is responsible for creating the standards on which HTML is developed today. These web development standards have been created as an attempt to unify the syntax and functionality developers create web pages with, as well as the feature set integrated in web browsers to enable these features in HTML. By writing web applications in a compliant markup that follows the HTML specification standards, developers can better ensure that their content will be displayed properly no matter how a user chooses to view it.

HTML syntax

Though it may look trivial, HTML syntax is the core of all web pages. Regardless of whether it is hardcoded within an HTML file, compiled from another programming language source, or injected into a document during application runtime, HTML syntax is the blueprint for the assets used within an HTML page. The better a developer understands HTML syntax and its limitations, the easier it will be for them to build their applications.

HTML syntax is written with the use of tag elements which are wrapped in angle brackets. HTML tags come in two different varieties: paired or empty elements. Paired HTML tags are the most common and the first tag style that one usually uses when creating an HTML document. The html tag is used to declare what is within an HTML document and usually sits on the first and last lines of an HTML file:

<html>
  Add your HTML content here.
</html>

As you can see in the previous example, paired tags open and close a container for more HTML elements to sit inside. Tags are always formatted the same, the only difference between each tag in the pair is that a forward slash is used to declare that a tag is closing an element. Therefore, <html> will not pair with any tag that does not contain the same internal value. HTML tags are case insensitive, and in the early days it was common for developers to always use capitals when writing tags. That tradition has now disappeared and you will almost always see tags written in lower case.

Empty HTML tags are written without the use of a closure tag. For example, when placing an image reference within an HTML document, there is no further HTML element content that can be placed within that image. Therefore, image references in HTML are formatted such as <imgsrc="my_image.jpg">. The image is referenced within the img tag by appending the src parameter with its value set to the image location.

Tip

If you have managed to use Adobe Flex to build any of your Flash content and utilized the MXML user interface markup language, you may have got the hang of closing empty tag elements with syntax such as <imgsrc="my_image.jpg" />. In HTML5, this trailing forward slash is not required but will still render your content properly if you happen to append it. For best use case, try to get in the habit of not using it in your HTML5 projects.

HTML is a tricky beast when it comes to debugging; a document with HTML errors in the syntax will not display errors on loading like a traditional Flash application. Writing clean and concise HTML is the key to maintaining an error-free, standard, compliant web page. There are many applications and tools available to aid in developing clean HTML code, some of which will be covered later in the book. The W3C has created a robust HTML syntax validation service, which will check a publicly available website for HTML errors (http://validator.w3.org/).

HTML elements

Every version of the HTML specification has a specific list of tags available to developers while creating HTML documents. The current list of elements within the HTML5 specification as defined by the W3C can be found within their language reference documentation (http://www.w3.org/TR/html-markup/elements.html).

Within the HTML5 specification are some very interesting new elements available to developers with regards to media integration into web pages. For example, Flash requirements for media playback can now be avoided when embedding audio or video into a web page with the addition of the audio and video tags. These exciting new media tags are covered in more depth in Chapter 3, Scalability, Limitations, and Effects.

Bringing in the style

Cascading Style Sheets or CSS is the primary method used for styling HTML elements. Like HTML, there is a set list of styles in CSS that you can apply to elements in an HTML documents. To get an idea of what CSS attributes are available to you, head over to http://www.w3schools.com/cssref/ for the entire list. CSS can be applied to HTML elements in a number of different ways. Traditionally, CSS syntax is stored within an external .css file and referenced from within the head element in an HTML document. However, CSS can be appended to elements within the HTML document directly by adding a style parameter to almost any element within the body tag:

<imgsrc="my_image.jpg" style="border:5px solid #000000;">

The previous example uses the style parameter within an image element to apply a 5-pixel thick black border around the image referenced in the src parameter.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

What if you had five images or even 100 images in your page that needed the same styles applied to each element? Applying the exact same style parameter to each image tag is not only time consuming but will result in code that is oversized and possibly extremely hard to maintain or update. CSS can target a single element or a group of elements by using a class or id HTML parameter:

<div id="photo-gallery">
  <imgsrc="photo1.jpg" class="photo">
  <imgsrc="photo2.jpg" class="photo">
  <imgsrc="photo3.jpg" class="photo">
  <imgsrc="photo4.jpg" class="photo">
  <imgsrc="photo5.jpg" class="photo">
</div>

In the previous example, we attempted to display a group of different images within an HTML document. Each image, referenced with an img element tag, also has a class parameter appended to it with the photo value. The class HTML parameter can be used and re-used on almost any element available and allow you to reference a group of elements rather than modifying each element directly. All of the images are also encased in a div element. div elements are used as containers to display content in. In this case, the div element has an id parameter set to photo-gallery. The id HTML parameter is very similar to class with the exemption of being able to re-use the same value of id within the same HTML document.

Tip

Editing HTML, CSS, and JavaScript can be simplified by using a code editing application setup to aid with HTML5 syntax. Applications like Aptana (http://aptana.com/), Dreamweaver (http://adobe.com/products/dreamweaver.html), and Sublime Text (http://sublimetext.com/) are all recommended. However, if simplicity is your thing, feel free to use something else.

With all this in mind, writing CSS to style this photo gallery could be done as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>My Photo Gallery</title>

    <!-- Our Photo Gallery CSS Styles -->
    <style type="text/css">
      body {
        background-color:#000000;
      }

      #photo-gallery {
        width:100%;
      }

      #photo-gallery .photo {
        width:200px;
        border:4px solid #ffffff;
      }
    </style>
  </head>
  <body>
    <div id="photo-gallery">
      <imgsrc="photo1.jpg" class="photo">
      <imgsrc="photo2.jpg" class="photo">
      <imgsrc="photo3.jpg" class="photo">
      <imgsrc="photo4.jpg" class="photo">
      <imgsrc="photo5.jpg" class="photo">
    </div>
  </body>
</html>

Instead of applying style parameter to each and every element in the document, we can now use the style tag within the head element to place our raw CSS code. In the previous example, HTML elements are selected in three different ways. To start, the body of the document had the background color set to black by using its hexadecimal value. We select the body tag element by simply using the tag reference. This method of selecting raw elements can be used on a wide variety of elements within your document but will affect all elements with that reference. The next method of selection is by looking for elements with a specific ID. To designate the use of an ID, # is placed in front of the ID value. Therefore, #photo-gallery will be selecting the div element with the id parameter set to photo-gallery. We set the width parameter of the gallery container to 100%, which is calculated from the browser width when viewing the HTML document. Finally, to style each one of the images in the gallery, we style the class which was applied to each one of the image tags in the body of the HTML document. Since the class HTML parameter can be applied to an unlimited number of elements in an HTML document, we can specifically target the classes within another element by chaining the CSS element selection together. Classes are selected in CSS by appending . to the start of the class name. Therefore, #photo-gallery .photo will select only the elements with the photo class name inside the element with id of photo-gallery:

Passing it over to JavaScript

Styling HTML elements with CSS only gets you so far. HTML and CSS are effectively the Flash IDE from the perspective of a Flash developer. What is missing is the code that drives the interaction and functionality within your application. While using Flash, ActionScript is the weapon of choice when creating robust applications. While developing HTML5 content, JavaScript will be doing the grinding, allowing you to bring life to your HTML elements.

What is JavaScript?

JavaScript has been around since the mid 1990s and has grown up to be one of the most popular scripting languages available. JavaScript brings life to HTML documents by adding features such as content modifications, animations, 3D graphics, form submission, and data retrieval all without having to reload the active HTML document. Features such as these allow web content to act more like traditional software applications rather than static web pages.

Unlike ActionScript 3, JavaScript is a true scripting language as it requires no preprocessing or compiling to be run. Just like HTML and CSS, a JavaScript document's source is sent to user upon request and executed on client side. Therefore, unlike technologies such as ActionScript, JavaScript source code is open for public viewing.

JavaScript in action

Looking back at our My Photo Gallery example, an important missing feature is the ability to view a selected photo in larger format. JavaScript is a perfect platform to add this functionality as its main usage is to bring interaction to HTML documents. Using the existing code example, we can extend its functionality by adding a new div element at the bottom of the page body to contain the larger image view. This element can be empty as we do not want a photo to be displayed by default on page load. Finally, we set an identifier on the div tag of id="photo-display", which will allow us to target the content in that element from CSS and JavaScript:

<div id="photo-display"></div>

Before integrating the JavaScript functionality, we need to append some CSS styles to div using #photo-display to allow selected photos to fill the browser window at a higher resolution, typical of most photo gallery displays. Within the CSS styles, we have already set for this example, we will append some more style properties to the #photo-display element:

#photo-display {
  display:none;
  position:absolute;
  top:0;
  width:100%;
  height:100%;
  background-color:#000000;
  text-align:center;
}

#photo-display img {
  margin:auto;
  margin-top:50px;
  max-height:800px;
  border:4px solid #ffffff;
}

This CSS will target only one specific div as we have used the #photo-display syntax to target it. To start the styles off, we begin with the most important parameter, display:none , which hides the element on page load. This is perfect in our case as we do not want the full-screen display visible on page load. By adding position:absolute and top:0 to the style definition for our #photo-display element, we will display the element on top of the previous elements declared within the HTML body. The rest of the styles set on #photo-display are pretty self-explanatory. The next lines of CSS specifically target the img elements within div with the photo-display class. We can do this in CSS by chaining identifiers together. In this case, we specify these styles for image tag elements within a custom named element ID.

With the HTML and CSS to display the larger version of a selected photo in place, the next step is adding the JavaScript code for displaying the selected photo within the #photo-display container upon user interaction. To consolidate this example into a single file, we will add the JavaScript within an HTML script element:

<!-- Our Photo Gallery JavaScript Source -->
<script>
  var largeImage = new Image();

  // Display a specific photo in the large
  // photo display element.
  var displayPhoto = function(source) {
    // If there is already an image inside the display
    // remove it.
    if(largeImage.src != '') {
      document.getElementById("photo-display").removeChild(largeImage);
    }

    // Update the source location of the image
    largeImage.src = source;
    document.getElementById("photo-display").appendChild(largeImage);

    // Display the large photo element.
    document.getElementById("photo-display").style.display = 'block';
  }

  // Closes the large photo display element.
  var closePhotoDisplay = function() {
    document.getElementById("photo-display").style.display = 'none';
  }
</script>

As a Flash developer, the previous function syntax should look pretty familiar. A major change within the function scope is the variable syntax. Unlike AS3, the HTML as well as the source variables are not strictly typed. This goes for all variables within JavaScript syntax and is probably one of the biggest issues Flash developers have with JavaScript.

Aside from some string manipulations to generate img HTML elements from the source variable, the method also references the document object. Every HTML document that is loaded into a browser then becomes the document object accessible from within JavaScript. The document object within JavaScript has a number of built-in properties and methods that are available to access information and elements within the view HTML document. In our example, we make use of the easily defined document object method getElementById(). As the method name implies, when an HTML element's ID is supplied, the reference to the element within the HTML document is returned for use within the script. Since JavaScript supports the chaining of properties, we can apply the innerHTML property to manipulate the inner content of an HTML element as well as the style property to change an element's CSS properties.

To enable an image to close once a user has finished viewing it, we will add a second JavaScript function to our example to revert all the changes made when displaying the photo. Since the photo-display image will be updated when the user clicks on a new image, all our closePhotoDisplay method needs to do is hide the visible element to show the full photo gallery again:

functionclosePhotoDisplay() {
  document.getElementById("photo-display").style.display = 'none';
}

Setting the #photo-display element's style.display back to none hides the entire element and reverts the user interface back to its initial state.

Adding events to each of the photos can easily be accomplished by appending an onclick parameter to the targeted element. The addition would look as follows:

<imgsrc="photo1.jpg" class="photo"onclick="displayPhoto('photo1.jpg')">

Now, when the image is clicked on, the onclick event gets fired and runs the JavaScript code declared within the parameter. In this case, we use this opportunity to call our displayPhoto method within our previously written JavaScript block. Within the call, we supply the required source variable, which will be the image file name as a String datatype. This will allow the proper image reference to be used within the #photo-display element. All put together, our updated div tag with id="#photo-gallery" will now look like the following:

<div id="photo-gallery">
  <imgsrc="photo1.jpg" class="photo"onclick="displayPhoto('photo1.jpg')">
  <imgsrc="photo2.jpg" class="photo"onclick="displayPhoto('photo2.jpg')">
  <imgsrc="photo3.jpg" class="photo"onclick="displayPhoto('photo3.jpg')">
  <imgsrc="photo4.jpg" class="photo"onclick="displayPhoto('photo4.jpg')">
  <imgsrc="photo5.jpg" class="photo"onclick="displayPhoto('photo5.jpg')">
</div>

Finally, to enable the user to close an open image within the #photo-display element, we will apply an onclick event to call our closePhotoDisplay method. Rather than applying the onclick event to the image within the #photo-display element, we will target the display itself, allowing users to click anywhere in the browser to close the display:

<div id="photo-display" onclick="closePhotoDisplay()"></div>

Putting all of these code snippets together, the gallery source now looks like the following:

<!DOCTYPE html>
<html>
  <head>
    <title>My Photo Gallery</title>

    <!-- Our Photo Gallery CSS Styles -->
    <style type="text/css">
      body {
        background-color:#000000;
      }

      #photo-gallery {
        width:100%;
      }

      #photo-gallery .photo {
        width:200px;
        border:4px solid #ffffff;
      }

      #photo-display {
        display:none;
        position:absolute;
        top:0;
        width:100%;
        height:100%;
        background-color:#000000;
        text-align:center;
      }

      #photo-display img {
        margin:auto;
        margin-top:50px;
        max-height:800px;
        border:4px solid #ffffff;
      }
    </style>

    <!-- Our Photo Gallery JavaScript Source -->
    <script>
      var largeImage = new Image();

      // Displays a specific photo in the large
      // photo display element.
      var displayPhoto = function(source) {
        // If there is already a image inside the display
        // remove it.
        if(largeImage.src != '') {
          document.getElementById("photo-display").removeChild(largeImage);
        }

        // Update the source location of the image
        largeImage.src = source;
        document.getElementById("photo-display").appendChild(largeImage);

        // Display the large photo element.
        document.getElementById("photo-display").style.display = 'block';
      }

      // Closes the large photo display element.
      var closePhotoDisplay = function() {
        document.getElementById("photo-display").style.display = 'none';
      }
    </script>
  </head>
  <body>
    <div id="photo-gallery">
      <!-- Place all of the images inline with a 'photo' class for CSS manipulation. -->
      <imgsrc="photo1.jpg" class="photo"onclick="displayPhoto('photo1.jpg')">
      <imgsrc="photo2.jpg" class="photo"onclick="displayPhoto('photo2.jpg')">
      <imgsrc="photo3.jpg" class="photo"onclick="displayPhoto('photo3.jpg')">
      <imgsrc="photo4.jpg" class="photo"onclick="displayPhoto('photo4.jpg')">
      <imgsrc="photo5.jpg" class="photo"onclick="displayPhoto('photo5.jpg')">
    </div>

    <!-- An empty DIV element to contain the user selected photo in large scale. -->
    <div id="photo-display" onclick="closePhotoDisplay()"></div>
  </body>
</html>

Saving the text into an .html file and launching it in a web browser will now reveal all of our hard work. Just as before, the gallery should start by displaying the list of images by default. Once an image is clicked on, the selection will be passed to the #display-window element and displayed at 100 percent of the browser width:

Finally, clicking anywhere within the document will close the large image and return you back to the initial gallery display.

Although this example contains none of the new features of HTML5, it is a simple way of showing some of the key technologies that make up HTML and some of the methods used to reference assets in HTML.

 

Why bother learning HTML5?


As a Flash developer, getting yourself into the realm of HTML5 development is an extremely logical step for many reasons. Building applications with HTML5 allows you to easily reach users on desktop or mobile with rich integrated and interactive content without the need for plugins. One of the most beneficial aspects of HTML5 development is the accessibility to the development environment. Since HTML5 requires no special compiler or software for writing code, developers are free to choose their favorite setup for writing and testing their projects. Applications can be easily run and tested within any compliant web browser and tested locally without the need of a web server. This makes HTML5 one of the most accessible and easy to use technologies on the Web.

Write once, deploy everywhere

Unlike Flash applications, any device with a modern web browser can interact with HTML5 web content. So, with the help of CSS for dynamic resizing of viewable content, your HTML5 applications can be used without the need of application installation or dependencies on desktop or mobile platforms. Developers can also use technologies such as Phone Gap (http://phonegap.com/) or Appcelerator (http://www.appcelerator.com/) to easily convert their existing HTML5 web content to packaged mobile applications for market in all modern mobile operating systems. Packaged applications can be integrated and sold using common mobile application services such as Apple's App Store (http://store.apple.com) and Google Play (https://play.google.com). On top of that, Microsoft Windows 8 desktop application development now supports a whole suite of different programming languages, one of them being HTML5 (http://msdn.microsoft.com/en-us/library/windows/apps/br211386.aspx). With the ability to package HTML5 content into installable applications, developers can now begin to easily monetize their work by sale on the various application distribution outlets.

Exciting new features

As just mentioned, HTML5 hosts a suite of new and exciting features, many of which will be covered in the following chapters of this book. However, to allow you to better understand why HTML5 is so exciting and important for Flash developers and the web development community, here is a more detailed list of some of those features.

canvas – 2D drawing API

Flash developers can really flex their programming abilities within the new canvas element and 2D drawing API. Just like the drawing API within ActionScript 3, the canvas HTML5 element allows developers to create dynamic graphics during runtime, all from within JavaScript. Flash game developers moving to HTML5 usually find their home within the utilization of the canvas element as it is the closest representation of traditional Flash development when using HTML5.

Media playback

Web developers no longer require to develop their media playback elements with platforms such as Flash or Quicktime. Audio and video can now be easily integrated into the HTML document using audio and video tags. Not only does this allow for easier and cheaper integration of playback elements into web pages but also mobile devices have no issues reading and displaying these elements from within their integrated browsers.

Offline storage

Traditionally, when web developers needed to save data locally on the user's machine, they used cookies. HTML5 adds a new offline storage method called Web Storage (http://dev.w3.org/html5/webstorage) that can drastically increase your applications' abilities when you have the requirement to save data for re-use. Large amounts of data like your clients user-specific application configuration can now be stored in a more secure and quicker manner.

You can now also setup your HTML5 content to be available to your users even when they go offline by utilizing the HTML5 cache manifest. The cache manifest is just a simple text file, which is placed on your web server. If a web browser supports the use of HTML5 cache manifests (all modern browsers currently do), the references to files and assets, which you have placed within the manifest, are all cached on the client side. Depending on whether your manifest is set to cache all the content required to run your application, the user can then go offline and continue using the application. Combined with the use of HTML Web Storage for archiving data to be resent to a web server upon Internet reconnection, you can develop applications that will allow your users to seamlessly use them despite their connection being broken. A perfect example of this feature of HTML5 in action is Gmail by Google (https://mail.google.com). By archiving message data on a user's device when accessed initially, important information such as e-mails can still be reviewed when a user goes to open a message while, say, he is underground in a subway.

Document editing

Many HTML5 elements now allow a parameter, contenteditable="true", which allows users to edit all the content within the element. This feature brings a sort of WYSIWYG environment directly to HTML content. Inline document editing can be extremely handy as a developer when manipulating content within your HTML5 projects.

Drag-and-drop

HTML5 elements now have the ability to be draggable. Simple but important user experience additions such as this bring more application-like interactivity which traditionally would be built with JavaScript. Just like inline document editing, setting elements to be draggable during development can aid in finding the proper position properties.

Geolocation

The Geolocation API enables users to allow their current position to be sent to an HTML5 document for use within JavaScript. Apart from the obvious usage of a user's location in mapping applications, Geolocation values can add many new features into web documents that allow for a more interactive user experience.

File API

The File API within HTML5 allows a more interactive experience when dealing with files on a user's local machine. Local files can now be dragged into the browser and previewed within the HTML document without uploading the data to the web server.

Tip

For a more in-depth look at the complete feature set within HTML5, visit the online W3C API documentation (http://www.w3.org/TR/html5/).

Mobile accessibility

As more devices become integrated with Internet accessibility, the need for streamlined, multiplatform applications that allow for low overhead and integrated device access is at an all-time high. Almost all modern mobile browsers already support many features of HTML5, which web developers can harness to build mobile applications that rival many natively built applications for specific mobile platforms. Features such as Geolocation, local file access and offline storage allow applications to easily integrate themselves into the device hardware that is running them.

Tip

Any of the examples in this book can be run on any modern mobile device running an HTML5-compliant web browser. If you have an iPhone, Android, or Windows phone handy, test out the examples on your device to view how well mobile platforms run HTML5 content.

One of the biggest driving forces behind the advent of HTML5 was mobile. Mobile application development requires a slightly different approach than typical application development as the platform running the application not only has fewer resources as compared to a typical desktop configuration but also things like battery life, screen resolutions, and touch interfaces need to be taken into account. Dealing with all of these requirements while developing applications with Flash can get a little bit tricky. Flash applications traditionally tend to be a bit heavy on resource usage, though optimizations can be made to compensate for some of these issues while running applications on mobile platforms.

Flash Player on Mobile

Since the advent of iPhone, Flash developers had to deal with the fact that their web-based Flash content would never be viewable from the integrated iOS web browser. Apple made their stance on the usage of the Adobe Flash Player clear in a publicly address letter from Steve Jobs in April 2010, which stated that the Flash Player did not deliver the device or application performance that Apple required on their device.

In June 2012, Adobe released a public statement regarding the future of the Adobe Flash Player for mobile. As of August 15, 2012, Flash Player for Android will only be available to devices certified to run the Flash Player as Adobe has suspended the development of the mobile version of Flash Player. Users running Android Version 4.1+ will be unable to run Flash content within their browser and all web content will rely on the use of the technologies within HTML5.

With the Flash Player removed from the mobile market, a Flash developer's only resource, at this point in time, for creating mobile applications is developing them with Adobe AIR and packaging their work as standalone applications rather than on the Web.

Build on your existing skillset

Flash developers transitioning to HTML5 development have a leg up when it comes to learning tricks to create amazing applications with purely HTML, CSS, and JavaScript. Not only will all the lessons learned about handling and optimizing media elements transition over, but also their ActionScript 3 skills will allow them to understand and use JavaScript to its full potential.

ECMAScript

The time developers invest to learn a programming language such as ActionScript 3 is far from a short endeavor. Fortunately, both JavaScript and ActionScript 3 are built on the ECMAScript scripting language standard (http://www.ecmascript.org). In a nutshell, this means that many of the method, variable, and property syntax setups are extremely similar in look, feel, and usage. As we dig deeper and see more examples of HTML5 in action, if you have experience with ActionScript 3, you will instantly notice many similarities when utilizing JavaScript.

 

Avoiding the initial road blocks


All Flash developers generally have the same issues when transitioning to HTML5 development. Most of these problems arise from differences between platform syntax, as well as dealing with the interaction between each element within the HTML5 stack.

Stage versus DOM

The first and most obvious change when moving to HTML5 development is the lack of the ever important Flash Stage. Dealing with element layout, asset animations, and interactivity with HTML5 is all taken care of purely with code. Although there are many web development IDEs with drag-and-drop type interfaces, to better understand how to build cleaner web pages, this book will cover all examples with hand written code examples.

Positioning assets in the DOM

One of the biggest initial issues many Flash developers have when moving into web development is the concept of positioning content and assets within the DOM. Unless specified, HTML elements are not simply placed in DOM with X and Y position values. Since elements within an HTML document are displayed inline by default, global X and Y position values are irrelevant. When positing an element within DOM with CSS, properties such as margin, padding, top, left, right, and bottom are used instead. As mentioned, if elements are specially styled with a position of absolute or utilized within a canvas element then X and Y values can be used. On top of the issues regarding simply controlling where elements are placed within your project, there is the ordeal of making sure that all of the web browsers that may view your content display it as per your specification.

Dealing with media elements

Media optimization is the key to delivering content over the Web. When working with Flash, many of the assets used are vector-based and therefore lightweight on the compiled SWF file size. Bitmap data used within the Flash SWF is compressed during compilation, therefore automatically aiding you by minimizing file size. Since what the majority of HTML documents do is reference raw files publicly accessible on the Web, each asset used should be optimized for minimal file size while keeping the intended quality as close to original as possible. As we cover different aspects of HTML5 development throughout the chapters of this book, many optimization methods will be covered for the different types of media used in web pages.

Securing your code

Publishing content in Adobe Flash outputs a compiled binary SWF file, which is ready to be played in a compatible Flash Player. The code and assets used in the application are protected from prying eyes since the application was compiled into a single binary file. But when dealing with code and assets on the Web, the entire game changes. Pretty much everything you create and deliver in an HTML5 project, as with any website, is open for public viewing.

Code obfuscation is a practice some developers use while delivering production level client-side code. Many websites and applications are available to obfuscate your JavaScript code by rewriting the code in a hard to read, compressed format. Although this is not a foolproof way of securing code, it adds a level of deterrence when it comes to users poking around a document's source code.

Understanding client-side code usage and limitations is the key to writing secure JavaScript applications. Sensitive information should never be hardcoded into a document which can be viewed on client side. Chapter 2, Preparing for the Battle, covers the usage of client-side script in a more in-depth manner in comparison to ActionScript 3.

Browser and platform compatibility

One of the major changes in development paradigm when moving from Flash to HTML5 development is the need to target multiple platforms with the same code base. While developing an application using Adobe Flash, you initially set a target version of the Flash Player for your application to run within. By compiling your application into a packaged SWF, the Flash runtime will have no issues rendering your application in any compatible Flash Player. Since every browser and platform tends to display web content a little bit differently, when developing HTML5 content and applications, one must take note of the platforms and browsers that may be used to view the content to better optimize the viewing experience.

Browser functionality checks can be written into JavaScript conditions to enable users with browsers that lack the support for specific HTML5 features to still view your HTML5 content. For instance, if a user visits a page with an HTML5 video playback element within it, without the support for it within his browser, JavaScript could alternatively embed a Flash video playback application instead.

Tip

Finding a modern web browser that doesn't support HTML5 is getting harder day by day. When it comes to choosing a browser to test code in while reading this book, Firefox (http://www.getfirefox.net/), Chrome (http://www.google.com/chrome), Safari (http://www.apple.com/safari/), and Opera (http://www.opera.com/) are all great choices and available online for free.

Within the chapters of this book, many of these popular web browsers will be utilized to show how content may sometimes differ in look and usage. Due to the speed at which browser updates and changes are released, testing your site as much as possible in every browser on every platform is a very important aspect of web development. Many of these web browsers now have built-in development and debugging tools, which allow for easier optimizations of your HTML5 projects. Other applications and services are also available to ease the pain of browser testing, some of which will be used and covered in this book.

 

Summary


In this chapter, we have covered the key aspects of the HTML5 stack and how to use each of them in a simplistic manner. By creating a simple photo gallery web page, we not only used HTML, CSS, and JavaScript, but also the methods to reference elements in between them. Some of the new and exciting features available within HTML5 were also explained and compared with functionality traditionally created within Flash assets. The typical issues during the learning curve for Flash developers moving to web development were reviewed to allow you to be aware of these issues before finding out the hard way. Hopefully, this chapter has furthered your interest in learning more about what HTML5 can do.

The development of the HTML5 standard maintained by the W3C is an interesting but extremely in-depth topic, which will not fit within the constraints of this book. If you are interested in learning more about how HTML5 standards are created and maintained, I strongly recommend checking out and keeping up with the information on specification and syntax development W3C publishes on their site (http://www.w3.org).

With the platform overview out of the way, we will continue by digging further into the most important aspect of the HTML5 stack, JavaScript, and how it relates to what you already know from developing with ActionScript.

About the Author
  • Matthew Fisher

    Matthew Fisher is a Software Engineer at Microsoft and one of the core maintainers of the Helm project. Born and raised on Vancouver Island, he studied computer systems at the British Columbia Institute of Technology. Outside of work, he has an extensive list of hobbies which is forever growing. On any given day, he is a musician, a luthier, a woodworker, a blacksmith, a cook, a photographer, and an artist. When he's not practicing with his guitar or rushing to and from the workshop, you'll find him out on another adventure with his wife, Brandy. He goes by the name @bacongobbler on GitHub and Twitter

    Browse publications by this author
HTML5 for Flash Developers
Unlock this book and the full library FREE for 7 days
Start now