Developing Windows Store Apps with HTML5 and JavaScript

By Rami Sarieddine
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. HTML5 Structure

About this book

Windows 8 has already been launched and been installed on millions of devices while the store is getting populated with apps, and soon enough everyone will want a Windows Store app. So start now and learn how to develop apps for Windows 8 using HTML5, CSS3, and JavaScript and you will be killing two birds with one stone by getting introduced to important features in HTML5 and CSS3 at the same time. You will gain the advantage of utilizing your web development skills to transform your website into an app or the other way round.

Developing Windows Store Apps with HTML5 and JavaScript is a practical, hands-on guide that covers the basic and important features of a Windows Store App along with code examples which will show you how to develop these features, all the while learning some of the new features in HTML5 and CSS3 which you can utilize in other areas of development.

This book starts with the new features in HTML5 and CSS3 that are incorporated with Windows 8 development, and then moves on to creating a blank Windows Store app and add features to it as we move through the chapters till we package the app and make it ready for publishing. Finally, we will have a look at how similar it is to develop the same app with XAML.

You will also learn how to add and use new controls dedicated for Windows 8 and then see how to fetch data for the app and bind it to the controls. We will also take a look at making the app adapt to change in screen sizes and rotation as well as how to make the app live with tiles and allow users to sign in using their email accounts. Also you will learn how to add an app bar, and lastly you learn how to finalize the app and publish it. If you want to leverage your web development skills and utilize it in developing for Windows 8, then you came to the right place. Developing Windows Store Apps with HTML5 and JavaScript is packed with examples and screenshots which will make it easy for you to implement all the things you learned throughout the book.

Publication date:
August 2013
Publisher
Packt
Pages
184
ISBN
9781849687102

 

Chapter 1. HTML5 Structure

HTML5 introduced new elements and attributes for a neater structure, smarter forms, and richer media; this make the life of a developer much easier. HTML5 features are classified into several groups based on their function, and the new structural elements fall under the group semantics, which include structural elements, media elements, attributes, form types, link relation types, semantics for internationalization, and microdata for additional semantics. There is a big list of additions and enhancements in HTML5, all with the aim of better presenting the content on the web. You will use many of these when developing apps for Windows 8; the difference and, moreover, the advantage of using it for Windows 8 development is that you do not have to worry about the browser's compatibility, at least at the level of Windows Store apps, since Windows 8 is an HTML5 platform that uses the most recent web standards. Everything that you use from HTML5 and CSS3 is provided for you in your code and is guaranteed to work in the application. And the latest version of Visual Studio (VS 2012) includes a new HTML and CSS editor that offers full support for HTML5 and CSS3 elements and snippets.

In this chapter we will be covering the following topics:

  • Semantic elements

  • Media elements

  • Form elements

  • Custom data attributes

 

Understanding semantic elements


HTML5 markup is more semantic than its predecessors due to the new semantic elements for describing the structure of the page content. The list of semantic elements includes the following:

  • The <header> tag defines a header for the document or section. It wraps the heading or a group of headings in a page or a section, and it can also contain information such as logos, banners, and main navigation links. You can have multiple <header> tags in a page.

  • The <nav> tag represents the major navigation links. Typically it is bound to the header.

  • The <section> tag wraps related content that can be grouped thematically. A <section> tag can include a <header> and <footer> tag.

  • The <footer> tag represents content about a page or a section, for example, related links, privacy terms, and copyright information. You can have more than one <footer> in a page, and it is same as the <header> tag.

  • The <article> tag represents self-contained content that can be used independent of the document as a whole, for example, a blog entry. <article> and <section> are much alike because both are standalone tags and hold related content; however, if it's content can be syndicated (via an atom or an RSS feed), then the <article> element is more appropriate.

  • The <aside> tag represents the part of a page that is tangentially related to the content around it, and also separate from that content, as it can be removed without affecting the main content of the page. Typical usage can be a sidebar.

  • The <address> tag represents the contact information for the nearest <article> parent element, if present, or the parent <body> element, which in that case applies to the whole document.

Putting all these new elements together in a page would yield the following markup:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Developing for Windows 8</title>
</head>
<body>
  <header>
    <a href="default.html">
      <h1>The Courses</h1>
      <img src="logo.png" alt="Book Logo">
    </a>
    <nav>
      <ul>
        <li><a href="home.html">Home</a></li>
        <li><a href="about.html">About</a></li>
      </ul>
    </nav>
  </header>
  <section>
    <article>
      <h2></h2>
      <p></p>
      <address>
        Written by <a href="mailto:[email protected]">Demo Author</a>.<br>
        Found at: Demo.com <br>
        Address, Street<br>
        UK
      </address>
    </article>
    <article>
      <h2></h2>
      <p>content</p>
    </article>
  </section>
  <aside>
    <h2></h2>
    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <p></p>
  </aside>
  <footer>
    <p></p>
    <p>Copyright &copy; 2013 Packt</p>
  </footer>
</body>
</html>
 

Introducing built-in media elements


HTML5 introduced new media elements such as <audio> and <video>, which can be considered as a new revolution in media types after images in the earlier versions of HTML. These two elements make it very easy to embed media in your HTML page/document and provide built-in media support via the HTML5 Media element API. According to the latest specs by W3C, we can define <video> and <audio> as follows:

  • The <video> tag is a media element used for playing videos or movies and audio files with captions

  • The <audio> tag is a media element whose media data is audio, that is, a sound or an audio stream

The <audio> and <video> elements play audio and video files respectively. The only difference between them is that the <audio> element does not have a playback area for visual content, contrary to the <video> element.

Prior to HTML5, we needed a plugin in order to play an audio or a video file, and that required writing a large chunk of markup. Without HTML5, embedding media elements was never so easy; just by putting an <audio> tag resulting in two lines of code you can get a media player with playback controls. It is almost the same as the <img /> tag before. Refer to the following code:

<audio src="audio.mp3" controls>
</audio>

The previous example results in a media player that will look like the following screenshot on Internet Explorer 9 (IE9), and might differ from one browser to another:

The previous code shows the <audio> tag in its simplest form, but the <audio> tag has more attributes and options. Refer to the following code:

<audio controls autoplay loop>
  <p>Your browser does not support the audio element. Click <a href="content/Elsie.mp3"> here </a> to download the file instead.
  </p>
  <source src="audio.mp3" type="audio/mp3" />
  <source src="audio.ogg" type="audio/ogg" />
</audio>

First, notice the content wrapped in a <p> tag inside the <audio> element. This content is a fallback text and will only be used if the browser doesn't support the <audio> tag. It provides a graceful fallback for older web browsers by informing the user about this issue, and we can add a link to allow the download of this audio file instead. This way, the user will not just stand there wondering what has happened. This is the simplest way to fallback; you can use JavaScript for the same purpose too.

The preceding code snippet also shows some of the attributes for the <audio> element. According to the W3C specification, src, controls, autoplay, loop, preload, mediagroup, and muted are common attributes to both the media elements, namely <audio> and <video>.

  • The controls attribute displays the standard HTML5 controls for the audio on the webpage, and the design of the controls varies between browser agents.

  • The autoplay attribute plays the audio file automatically as soon as the DOM finishes loading.

  • The loop attribute enables repetition automatically.

  • The mediagroup attribute links multiple media elements together using a media controller.

  • The muted attribute sets a default state of the audio file to mute.

  • The preload attribute provides a hint to the user agent about what the author thinks will lead to the best user experience. Its values can be none, metadata, or auto.

    • none: This value hints to the browser that the web page doesn't expect users to need the media resource.

    • metadata: This value hints to the browser to fetch the resource metadata (dimensions, track list, duration, and so on).

    • auto: This value hints to the browser to put the user's needs first without any risk to the server. An empty value, as in just adding the attribute preload, maps to the auto value.

You can specify a value for the attributes as in controls="controls", which would have the same behavior. But for simplicity and less code, you can simply leave out the value for this attribute; the same can be applied for loop, autoplay, and muted. You can specify the media resource by either using the src attribute or the <source> elements.

Note

The attribute overrides the elements.

The media resource (audio or video) has a MIME type and additionally a codec as in the following code:

<source src="video.ogv" type="video/ogg; codecs="theora, vorbis" />

Setting the value for the type attribute has to be done within the <source> element. The browser/user agent will avoid downloading the resource if it does not support its type. You can add multiple formats of your audio/video in order to ensure playback support across different browsers. The browser agent will go over the <source> elements; if it cannot render the first type, it will skip to the next <source> to validate its type, and so on. For this purpose, you will have to check the list of MIME types supported by the <audio> and <video> elements in different browsers. The browser not only checks for the MIME types but also for the specified codec. So, even if the browser agent can render the resource type, the video/audio will not load if the codec is not supported.

The following table lists the support for the 3 main video formats across the major browsers:

Format

IE9+

Chrome

Firefox

Opera

Safari

WebM (VP8 CODEC)

Yes

Yes

Yes

Yes

No

MP4 (H.264 CODEC)

Yes

Yes

No

No

Yes

OGV (OGG THEORA CODEC)

No

Yes

Yes

Yes

No

From the listing in the previous table, we can conclude that providing a media resource with both WebM and MP4 formats in your HTML5 video will guarantee it to load in the latest versions of all major browsers. This theory is reinforced in Visual Studio 2012, which offers full Intellisense support for HTML5 tags. When you insert the following snippet for an HTML5 <video> element, it lists 3 <source> elements within the <video> tag:

<video controls="controls">
  <source src="file.mp4" type="video/mp4" />
  <source src="file.webm" type="video/webm" />
  <source src="file.ogv" type="video/ogg" />
</video>

The <video> element also includes a poster attribute, which is used to specify a path for an image to be displayed in the visual content area when no video data is available or until the user clicks on the play button. For advertising purposes, you can use an image or a frame from the video that gives the user an idea of what the video is like. If you do not specify a poster image and if the autoplay attribute is not set, the browser may just display a black box filling the dimensions of the <video> element. For example, the following code shows the difference between code samples for two similar videos, with a poster specified for the second video:

<video id="video" controls width="400">
  <source src="http://ie.microsoft.com/testdrive/Videos/BehindIE9AllAroundFast/video.mp4" type="video/mp4" />
</video>
<video id="videoWithPoster" controls width="400" poster="http://msdn.microsoft.com/br211386.5_GetStarted_484x272px.jpg">
  <source src="http://ie.microsoft.com/testdrive/Videos/BehindIE9AllAroundFast/video.mp4" type="video/mp4" />
</video>

The output of this markup will produce the following on the screen:

You might have noticed that we specified a width value of 400 for the two videos in the previous example. The <video> element accepts standard HTML width and height attributes. If there is no value set for width and height, the visual content area stretches to the native size of video. It is recommended to set the width and height attributes on the <video> element, thus avoiding stretching to full size, and to encode the video at the desired viewing dimensions.

Note

The values for the width and height attributes do not accept units. The value indicates CSS pixels, for example, width=400 is the same as width=400px.

There are JavaScript methods, properties, and DOM events that are part of the HTML5 standard that is associated with these new elements. You can read and set properties programmatically, such as the src path and the dimensions (width and height) of the <video> tag. You can use JavaScript methods to load the audio and video, and then play and pause the media resource. You can also write code to handle different DOM events raised by media elements, such as onplaying, onprogress (load progress), onplay, and onpause. For example, you disable the default controls displayed by the element by removing the controls attribute and by calling the functions that play and pause the media resource from separate buttons.

The following code listing shows how we can play and pause the video using JavaScript. We first need to detect the current state of the video file by calling the Boolean property .paused, and if true, we then call the methods play() or pause() accordingly:

var testVideo = document.getElementById('myVideo');
if (testVideo.paused)
  testVideo.play();
else
  testVideo.pause();

In the preceding code, we declare a variable testVideo and assign it to the myVideo element from DOM. Assuming that the element was assigned an ID, you can use the name, tag name, or the element's place in the DOM hierarchy to retrieve the elements.

Advanced media with JavaScript

The media elements have a rich API to access with pure JavaScript. Using JavaScript, we can add a lot of functionality to the media elements. You can manipulate the media resource, style it, rotate a video, play two and more media elements in sync, display a progress bar while the media resource loads, resize a video dynamically, and so on.

The following is the code sample that adds functionality to the timeupdate event, which fetches the current play time of the video in seconds and displays it in a separate div.

The following is the HTML code:

<div id="tInfo"></div>
<video id="myVideo" autoplay controls>
  <source src="w8.mp4" type="video/mp4" />
</video>

The following is the JavaScript code:

var video = document.getElementsById('myVideo');
var tInfo = document.getElementById('tInfo');
video.addEventListener('timeupdate',function(event){
tInfo.innerHTML = parseInt(video.currentTime);
}, false);

The JavaScript addEventListener method is used to provide a handler for the timeupdate event. It takes three parameters and has the basic syntax, which is as follows:

WinJS.Application.addEventListener(type, listener, capture);

The type parameter specifies the type of event to register, while listener is the event handler function to associate with the event, and the third parameter capture is a Boolean value that specifies whether the event handler is registered for the capturing phase or not.

In addition, you can combine the capabilities of the <video> element with a canvas, allowing you to manipulate video data in real time and add a variety of visual effects.

 

Introducing feature-rich form elements


Forms and <form> elements are an integral part of any application or website, from a login form to a complete contact or registration form. In HTML4, the <form> elements were very idle, and for any feature or advanced styling, JavaScript was a necessity. And for any interaction, or data submission and validation, it demanded server and client-side scripting, and its functionality was inhibited if the scripting was disabled in the browser. HTML5 brought major improvements to the <form> elements with new attributes and input types, and added features such as browser-based validation and CSS styling that provide a better experience for the users filling it, and all possible simplicity for the developers creating it.

An enriched <input> tag

New values for the type attribute are introduced to the <input> element.

HTML5 adds 13 new <input> types to the ones we were already familiar with in HTML4, such as text and checkbox. With this addition, the <input> control now supports types such as range, date, number, telephone, email, and URL. And these new <input> types add intelligent behavior to the element themselves.

The following is the table listing of these types:

<input> types

Description

tel

It expects a telephone number.

search

It prompts the user to enter text that they want to search for, and adds a search icon to the input element (on browsers that support it).

url

It expects a single URL.

email

It expects a single e-mail address or a list of e-mail addresses (separated by commas).

datetime

It expects a date and time with UTC time zone.

date

It expects a date.

month

It expects a date with a year and a month, but no time zone.

week

It expects a date that consists of a week-year number and a week number.

time

It expects a time-value such as hours, minutes, seconds, and fractional seconds.

datetime-local

It expects date and time with no time zone.

number

It expects numerical input.

range

It expects a numerical input and displays a slider.

color

It expects color value and displays a color palette to choose from.

Along with the addition to the <input> types, new features have been added to the already existing ones such as the File input element, which now supports multifile selection using the multiple attribute. The browse button will display the file dialog and then you can select files from your local disk or SkyDrive; the files can be sent to the server as part of the form data when the form is submitted.

You can also take advantage of the progress element that represents the progress of a task, as specified by the W3C. It can be used to show the progress of a large file being uploaded or a media resource that is being loaded. The progress of a task is determined by two attributes of this element:

  • The value attribute, which indicates how much progress has been made

  • The max attribute, which indicates the total amount of work required till task completion

The following code uses a progress element and a button, and the script adds the value specified in the JavaScript function parameter to its existing value. When you load the sample and try it, you will see the progress bar visually updating the completion progress.

The following is the HTML code:

<button id="clickBtn" onclick="updateProgress(10)">Update Progress</button>Progress: <progress id="prog" max="100"></progress>

The following is the JavaScript code:

<script>
//get the progress element and add the value to it with every click var progressBar = document.getElementById('prog');
function updateProgress(newValue){ 
progressBar.value = progressBar.value + newValue;
}
</script>

Easy validation

HTML5's new <input> types along with the validation attributes such as required and pattern, and the pseudo CSS3 selectors allow browser-based validation, where you can catch a form's input errors without a single line of code or script. This was previously impossible and needed a custom JavaScript code or a JavaScript library. Basically, it provides client-side form validation without JavaScript.

We'll start with the most trivial validation, filling a required field. In order to achieve this, we need to add the required attribute to an <input> element.

The required attribute can be set on the <input> elements with type text, URL, email, checkbox, or radio, and on select and textarea elements. It is a Boolean attribute and can only be set on an element.

We specify that filling a value for a field is mandatory by simply adding the required attribute. In the following code listing, you will find a couple of <input> elements with the required attribute:

<form action="/" method="post">
  <label>Checkbox:</label>
    <input type="checkbox" required />
  <label>Radio:</label>
    <select>
      …
    </select>
  <label>Text:</label>
    <input type="search" required />
  <label>Range:</label>
    <input type="range" min="5" max="10" step="5" />
  <label>URL:</label>
    <input type="url"  required />
  <label>File:</label>
    <input type="file" accept=".mp3" />
    <input type="submit" name="submit" value=" Submit " />
</form>

Once the required attribute is added, and then when you click on the submit button, all the fields in the form will be validated; an error is returned if any of the fields are incorrect. The required fields are highlighted, and moreover, default messages are provided to notify the user that these fields are required in the form.

You can see the following screenshot displaying the output of the preceding code:

We can apply one or more styles using the CSS3 pseudo-selector required (more on that in the next chapter). For example, the following style adds a CSS3 pseudo-class required, which will look for all the input elements in the document that have the required attribute, and style it with the yellow border-color.

input:required {
  border-color: Yellow;
}

If you want to apply a style that affects all the non-required elements in the form, well that's very easy; just add the optional pseudo-class and give it a style just as we did with the required class. In the following code, we apply a LightGray border-color to all the input elements that don't have a required attribute.

input:optional {
  border-color: LightGray; 
}

HTML5 forms not only validate for required fields, but they also check the content of the field values and validate it either automatically, as in the URL and email input types, or by using the pattern attribute. The pattern attribute uses a regular expression to define the valid format that the element value must match, for example, a telephone number or social security number.

The following example shows the syntax for a password field, which is both required and must have a valid input with a minimum length of eight characters. And here, the default validation message is replaced by the text provided in the title attribute:

<input type="password" required pattern="[^\s]{8}[^\s]*" title="Passwords must be at least 8 characters long."/>

There are more attributes that add to the validation technique, such as placeholder, which provides the users with a hint message displayed in light text until the user starts typing inside the element; the hint could be about the value they should enter in the field. For example, you can add a demo e-mail address in the email field such as:

<input type="email" placeholder="[email protected]" />

You can check for the maximum number of characters allowed in a text or a textarea input using the maxlength attribute. Also, we have the min, max, and step attributes used with the range element to validate the values entered for that element. The min and max attributes check for the minimum and maximum values that can be entered, while the step attribute checks for the allowed values.

You can also specify acceptable file MIME types with the accept attribute. As you may have noticed in the preceding code listing, the accept attribute was added to the <input type="file" /> element, which is the only element to be used with it. Once you add this to the file control, and then when you try to browse for a file using Windows 8 File Explorer, only the types that are in the accept list will be displayed.

HTML5 form validation is the default behavior; no code is needed to activate it, but you can turn it off by adding the formnovalidate attribute to the submit button or any <input> element. This attribute allows a form to be submitted without being validated.

 

Assigning custom data attributes


With HTML5, we now have the ability to assign custom data attributes to any HTML5 element. The W3C defines it as:

Attribute that is intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

These new custom data attributes consist of two parts:

  • Attribute name: It must start with the prefix data- and should be followed with at least one character and should not contain uppercase characters

  • Attribute value: It must be a string value

Let's add a custom attribute to a <div> tag as shown in the following code:

<div id="bookList" data-category="TechnicalBooks">
Developing for windows 8
</div>

You can see the custom attribute name data-category and the attribute value TechnicalBooks assigned to the <div> element. This data can be retrieved and updated by your JavaScript code using the native getAttribute and setAttribute methods, because the custom data attributes are considered to be part of the page on which they are used. The following is the code sample that shows how to manipulate the custom attributes using native JavaScript:

function getSetCategory() {
  var bookList = document.getElementById("bookList");
//get the value of the attribute
  var bookCategory = bookList.getAttribute('data-category');
//set the value for the attribute
  bookList.setAttribute('data-category', 'HealthBooks');
//remove the attribute
  bookList.removeAttribute('data-category');
}

The HTML5 specification clearly states that the data attributes should not be used to replace an existing attribute or an element that may be more semantically appropriate. For example, it would be inappropriate to add a data-time attribute to specify a time value in a span element as the following code shows:

<span data-time="08:00">8am<span>

The most appropriate and more semantic element to use would be a time element, as the following code shows:

<time datetime="08:00">8am</time>

When developing Windows 8 apps, we can use the Windows library for JavaScript (WinJS) to achieve more advanced binding of data to HTML elements. The Win8 JavaScript library utilizes the HTML data-* attributes to provide an easy way to programmatically implement data binding.

 

Summary


In HTML5, there are new semantically rich elements that can convey the purpose of their use. There are media elements that allow you to easily add audio and video to your application, and new input types and attributes that you can use to create intelligent and interactive forms and bind them to data on-the-fly, all with less markup and code than ever before.

In the next chapter, we will have a look at the new and rich CSS3 features available for us when developing for Windows 8, and how we can use them to style and apply layouts to our HTML.

About the Author

  • Rami Sarieddine

    Rami Sarieddine is a passionate technology evangelist and a subject matter expert in web development, Windows apps, and Microsoft Azure. He is currently working as a Technical Evangelist with Microsoft. This is his second publication, following his first book Developing Windows Store Apps with HTML5 and JavaScript, Packt Publishing (https://www.packtpub.com/application-development/developing-windowsstore-apps-html5-and-javascript#).

    He has more than 8 years of experience in programming for the Web. He was awarded the Microsoft Most Valuable Professional status twice, in 2012 and 2013, for his contributions to the technical communities of ASP.NET/IIS and Visual C#. He has featured as a regular speaker at key technical events for Microsoft Lebanon, including Open Door and TechDays. He has delivered hundreds of training sessions on HTML5, JavaScript, Azure, and Visual Studio.

    When not working, Rami enjoys running and spending time with his loved ones. And when on vacation, he enjoys traveling and visiting new places around the world.

    He can be reached via his e-mail ID, [email protected] You can follow his tweets as well; his Twitter handle is @ramiesays. You can also find his blog posts on http://code4word.com.

    Browse publications by this author
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial