API usage

Now that we've discussed what all of the game elements are and how each HTML5 feature was used to fulfill that role, let's take a deeper look at how to make the most out of each of these APIs. For each of the following APIs, we'll provide a more concrete definition of the feature, what its intended use is, and a code example will follow. You may also refer to the complete source code attached at the end of the chapter in order to fill the gap between the code sample and how that feature fits in with the rest of the game code base. It is also recommended that you code along and play with the various settings and values in order to experiment with and more fully understand each API.

Web forms

The new HTML5 web forms API adds 13 new input types that allows for a much more flexible and powerful experience. What's more, web forms are also able to validate themselves requiring zero JavaScript intervention.

New input types

The following are the new input types defined in the new web forms chapter of the HTML5 specification:

Date

The date input type allows the user to select a specific date from a browser-supplied calendar. The specific format and styling of this calendar is unique to the browser and platform used. The data that results from a date selection is of the form YYYY-MM-DD.

<input type="date"
  min="1935-12-16"
  max="2013-08-19"
/>

The optional attributes min and max can be used to force validation of the date selected by the user to be within a given range. Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user, so inputting a stored value in the future can be automatically completed by the browser upon hint by user
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading
  • min (value must be a valid date in the form of "yyyy-mm-dd"): Specifies the lowest date allowed to be selected by the user
  • max (value must be a valid date in the form of "yyyy-mm-dd"): Specifies the highest date allowed to be selected by the user
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit
  • value (value must be a valid date in the form of "yyyy-mm-dd"): Specifies the actual date represented by this element

Month

The month input type allows the user to select a specific month and year from a browser-supplied calendar. The specific format and styling of this calendar is unique to the browser and platform used. The data that results from a date selection is of the form YYYY-MM.

<input type="month"
  min="1935-12"
  max="2013-08"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading
  • min (value must be a valid date in the form of "yyyy-mm"): Specifies the lowest date allowed to be selected by the user
  • max (value must be a valid date in the form of "yyyy-mm"): Specifies the highest date allowed to be selected by the user
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit
  • value (value must be a valid date in the form of "yyyy-mm"): Specifies the actual date represented by this element

Week

The week input type allows the user to select a specific week of a year from a browser-supplied calendar. The specific format and styling of this calendar is unique to the browser and platform used. The data that results from a date selection is of the form YYYY-Www (for example, 2013-W05).

<input type="week"
  min="1935-W51"
  max="2013-W34"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading
  • min (value must be a valid date in the form of "yyyy-Www", where "ww" must be a two digit representation of the week number): Specifies the lowest date allowed to be selected by the user
  • max (value must be a valid date in the form of "yyyy-Www", where "ww" must be a two digit representation of the week number): Specifies the highest date allowed to be selected by the user
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit
  • value (value must be a valid date in the form of "yyyy-Www", where "ww" must be a two digit representation of the week number): Specifies the actual date represented by this element

Time

The time input type allows the user to select a specific time of day. The data in this element is of the form HH:MM:SS.Ms.

<input type="time"
  min="16:23:42.108"
  max="23:59:59.999"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading
  • min (value must be a valid partial time in the form of "HH:MM:SS.Mss", "HH:MM:SS", or "HH:MM"): Specifies the lowest date allowed to be selected by the user
  • max (value must be a valid partial time in the form of "HH:MM:SS.Mss", "HH:MM:SS", or "HH:MM"): Specifies the highest date allowed to be selected by the user
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit
  • value (value must be a valid partial time in the form of "HH:MM:SS.Mss", "HH:MM:SS", or "HH:MM"): Specifies the actual date represented by this element

Datetime

The datetime input type allows the user to select a specific date and time (including time zone) from a browser-supplied calendar. The specific format and styling of this calendar is unique to the browser and platform used. The data that results from a date selection is of the form YYYY-MM-DDTHH:MM:SS-UTC.

<input type="datetime"
  min="1935-12-16T16:23:42-08:00"
  max="2013-08-19T23:59:59-09:00"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading
  • min (value must be a valid date time, as defined in the RFC 3339): Specifies the lowest date allowed to be selected by the user
  • max (value must be a valid date time, as defined in the RFC 3339): Specifies the highest date allowed to be selected by the user
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit
  • value (value must be a valid date time, as defined in the RFC 3339): Specifies the actual date represented by this element

Datetime-local

The datetime-local input type allows the user to select a specific date and time (not including time zone) from a browser-supplied calendar. The specific format and styling of this calendar is unique to the browser and platform used. The data that results from a date selection is of the form YYYY-MM-DDTHH:MM:SS.

<input type="datetime-local"
  min="1935-12-16T16:23:42"
  max="2013-08-19T23:59:59"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading
  • min (value must be a valid partial time in the form of "YYYY-MM-DDTHH:MM:SS.Mss", "YYYY-MM-DDTHH:MM:SS", or "YYYY-MM-DDTHH:MM"): Specifies the lowest date allowed to be selected by the user
  • max (value must be a valid partial time in the form of "YYYY-MM-DDTHH:MM:SS.Mss", "YYYY-MM-DDTHH:MM:SS", or "YYYY-MM-DDTHH:MM"): Specifies the highest date allowed to be selected by the user
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit
  • value (value must be a valid partial time in the form of "YYYY-MM-DDTHH:MM:SS.Mss", "YYYY-MM-DDTHH:MM:SS", or "YYYY-MM-DDTHH:MM"): Specifies the actual date represented by this element

Color

The color input type allows the user to select a specific color from a browser-supplied color picker. The specific format and styling of this color picker widget is unique to the browser and platform used. Although some implementations of the widget may provide values in different format (RGB or HSL), the data that results from a color selection is a hexadecimal representation of the color in the form #RRGGBB.

<input type="color"
  value="#900CC1"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • value (value must be a valid hexadecimal color with exactly seven characters in length and of the form "#rrggbb" or "#RRGGBB"): Specifies the actual color represented by this element. Keywords, such as Color, are not allowed.

Email

The email input type allows the user to input an e-mail address. In mobile devices where a digital keyboard is provided for data entry, this input type hints to the system that the keyboard to be provided should be the most appropriate for entering an e-mail address.

<input type="email"
  placeholder="Enter an email address"
  pattern="w{3,}@packtpub.com"
  maxlength="23"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • maxlength (value must be a non-negative integer): Specifies the maximum length of characters that the element can contain.
  • pattern (value must be a valid regular expression pattern as defined by ECMA 262): Specifies a pattern that the browser must validate the specified input against.
  • size (value must be a positive integer): Specifies the maximum number of characters displayed by the element, although more characters may be allowed to be entered.
  • placeholder (value must be a string): Specifies a string to be shown to the user as a hint as to what information the field expects. This string disappears when data is entered into the field and is shown when the field becomes empty.
  • multiple (acceptable values include multiple, "", or empty): Specifies that multiple values are allowed in this element.
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user.
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit.
  • value (value must be a valid e-mail address and must adhere to any further restrictions specified by the pattern attribute, if any): Specifies the actual e-mail address represented by this element or a comma-separated list of valid e-mail addresses when the multiple attribute is present.

Note

For those not familiar with JavaScript's regular expression language, or who need a refresher, following is a summary of the syntax:

[rodig] (brackets): used to match anything found within the brackets. For example: match any one of the letters within the brackets.

[^rodig] (negative brackets): Used to match anything not found within the brackets. For example, match any character except one of the letters within the brackets.

[D-M] (range): Used to match a range of characters or numbers. For example, match any characters between the capital letters D and M.

(me|you|us) (pipe): Used to match alternative options. For example, match either of the words within the parenthesis.

. (period): Match any characters, expect for a new line character or a line terminator character.

w (word character): Match any letter, number, or an underscore.

W (non-word character): Match any character that is not a word characters.

d (digit): Match any single digit.

D (non-digit): Match any non-digit character.

s (space): Match a white space.

S (non-space): Match any character that's not a space character.

 (word boundary): Find a match at the beginning or end of a word.

B (non-word boundary): Find a match that is not a word boundary.

(null character): Matches the NULL character in a string.

(new line character): Matches the new line character.

f (form feed character): Matches the form feed character.

(return carriage character): Matches the form carriage character.

(tab character): Matches the tab character.

v (vertical tab): Matches a vertical tab character.

+ (plus quantifier): Matches the previous expression or character one or more times.

* (star quantifier): Matches the previous expression or character zero or more times.

? (question mark quantifier): Matches the previous expression or character zero or one time.

{3,5} (bracket quantifier): Matches the previous expression a minimum and maximum of times respectively. If the maximum digit is missing, the matches will continue until a non-match is found. For example: d{1,} matches one or more digits.

^ (hat modifier): Matches an expression at the beginning of a string.

$ (dollar modifier): Matches an expression at the end of a string.

Number

The number input type allows the user to select number from any mechanism provided by the browser or to simply enter a numerical value if only a standard input field is provided by the browser. The value is validated by the browser to ensure that a number is indeed entered by the user. In mobile devices, where a digital keyboard is provided for data entry, this input type hints to the system that the keyboard to be provided should be the most appropriate for entering numbers.

<input type="number"
  min="42"
  max="108"
  step="2"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • min (value must be a floating point number): Specifies the lowest number allowed to be selected by the user.
  • max (value must be a floating point number): Specifies the highest number allowed to be selected by the user.
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user.
  • placeholder (value must be a string): Specifies a string to be shown to the user as a hint as to what information the field expects. This string disappears when data is entered into the field and is shown when the field becomes empty.
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change.
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit.
  • value (value must be a floating point number): Specifies the actual floating point number represented by this element.

Range

The range input type allows the user to select a number from a specified range using a browser-supplied slider widget. The specific format and styling of this slider widget is unique to the browser and platform used. The data that results from a range selection is a floating point number.

<input type="range"
  min="42"
  max="108"
  step="0.5"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • min (value must be a floating point number): Specifies the lowest number allowed to be selected by the user.
  • max (value must be a floating point number): Specifies the highest number allowed to be selected by the user.
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user.
  • placeholder (value must be a string): Specifies a string to be shown to the user as a hint as to what information the field expects. This string disappears when data is entered into the field, and is shown when the field becomes empty.
  • step (acceptable values include any or any positive integer): Specifies how the value attribute of the element is to change.
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit.
  • value (value must be a floating point number): Specifies the actual floating point number represented by this element.

Search

The search input type allows the user to enter a string intended for a search. Overall, the search input type looks and behaves very much like a regular text input type. Some browsers might add miscellaneous behavior to this field, such as built-in icons or widgets to instantly clear the field, but none of these are officially part of the specification.

<input type="search"
  placeholder="Search"
  pattern="[^!?]"
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled, and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • maxlength (value must be a non-negative integer): Specifies the maximum length of characters that the element can contain.
  • pattern (value must be a valid regular expression pattern as defined by ECMA 262): Specifies a pattern that the browser must validate the specified input against.
  • size (value must be a positive integer): Specifies the maximum number of characters displayed by the element although more characters may be allowed to be entered.
  • placeholder (value must be a string): Specifies a string to be shown to the user as a hint as to what information the field expects. This string disappears when data is entered into the field and is shown when the field becomes empty.
  • multiple (acceptable values include multiple, "", or empty): Specifies that multiple values are allowed in this element.
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user.
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit.
  • value (value must be a string with no line feed or carriage return character): Specifies the actual search query represented by this element.

Tel

The tel input type allows the user to enter a telephone number.

<input type="tel"
  placeholder="Enter your phone number"
  required
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • maxlength (value must be a non-negative integer): Specifies the maximum length of characters that the element can contain.
  • pattern (value must be a valid regular expression pattern as defined by ECMA 262): Specifies a pattern that the browser must validate the specified input against.
  • size (value must be a positive integer): Specifies the maximum number of characters displayed by the element although more characters may be allowed to be entered.
  • placeholder (value must be a string): Specifies a string to be shown to the user as a hint as to what information the field expects. This string disappears when data is entered into the field and is shown when the field becomes empty.
  • multiple (acceptable values include multiple, "", or empty): Specifies that multiple values are allowed in this element.
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user.
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit.
  • value (value must be a string with no line feed or carriage return character): Specifies the actual phone number represented by this element.

Url

The url input type allows the user to enter a website url.

<input type="url"
  placeholder="Enter your website address"
  required
/>

Other valid attributes for the date input type include the following:

  • name (value must be a string): Identifies a particular field by the string value associated with the attribute.
  • disabled (acceptable values include disabled, "", or empty): Specifies that the element is disabled, and cannot receive control.
  • autocomplete (acceptable values include on or off): Specifies whether the browser should store values entered by the user so inputting a stored value in the future can be automatically completed by the browser upon hint by user.
  • autofocus (acceptable values include autofocus, "", or empty): Specifies to the browser that the element must receive focus immediately after the document finishes loading.
  • maxlength (value must be a non-negative integer): Specifies the maximum length of characters that the element can contain.
  • pattern (value must be a valid regular expression pattern as defined by ECMA 262): Specifies a pattern that the browser must validate the specified input against.
  • size (value must be a positive integer): Specifies the maximum number of characters displayed by the element although more characters may be allowed to be entered.
  • placeholder (value must be a string): Specifies a string to be shown to the user as a hint as to what information the field expects. This string disappears when data is entered into the field and is shown when the field becomes empty.
  • multiple (acceptable values include multiple, "", or empty): Specifies that multiple values are allowed in this element.
  • readonly (acceptable values include readonly, "", or empty): Specifies that the value of this element cannot be changed by the user.
  • required (acceptable values include required, "", or empty): Specifies that this element must have a valid value in order for the form to be allowed to submit.
  • value (value must be a string with no line feed or carriage return character): Specifies the actual url represented by this element.

Form validation

Although a form submission will automatically validate data inserted into the form and alert the user of any possible errors, there is a nicely defined API that gives us much more control over the validation process and reporting, than just the default.

Validity state object

Each form element has an object attached to it of type ValidityState , which contains a list of properties related to the validation status of that node. You can access this object directly from a form element and inspect its properties manually:

var firstName = document.querySelector("#myForm input[name='firstName']");
//firstName.validity == ValidityState {
  valid : false,
  customError : false,
  badInput : false,
  stepMismatch : false,
  rangeOverflow : false,
  rangeUnderflow : false,
  tooLong : false,
  patternMismatch : false,
  typeMismatch : false,
  valueMissing : false
}

With these properties, we're able to inspect each form element and really customize the validation routine for the form. However, seeing that automatic validation is such an attractive feature designed to save time and effort, we'll focus on the functionality that can best help us with respect to this auto validation.

Custom validation

One of the properties of ValidState is the Boolean customError, which specifies whether a custom error message has been set to the field element or if the browser is to display a generic error message for this element in case the form does not validate. To set a custom error message, we can call the setCustomValidity() method of the form element itself and assign a message for the browser to use when needed, as follows:

var email = document.querySelector("#myForm input[type='email']");
email.pattern = "\w{3,}@packtpub\.com";
email.setCustomValidity("Please enter a valid Packt email address...");
Custom validation

The first entry in the form just seen is invalid because it doesn't contain the string packtpub.com. The second form is valid because it conforms to the pattern specified. Note the customized error message on the first form, which is guaranteed to be the same in any browser that supports the features, as opposed to having a generic error message which can vary from browser to browser.

Used in the game

There were two separate instances in the game where the web forms API was used. The first was in the game options widget, where a range input type was used to allow the user to select the difficulty of the game, and the other was used in the new champion form, allowing the user to enter his or her full name along with an email address.

<nav id="navOptions">
  <div>
    <p>Difficulty &raquo; <span>1</span></p>
    <input type="range" step="1" min="1" max="3" value="1" />
  </div>
  <img src="img/options-icon.png" />
</nav>

Here we set up a basic range input, specifying the maximum value as 3. By default, most browsers will set the value for the step, min, and value attributes all to 1, but just to be safe, we'll specify those values in case a browser handles that differently in case the attributes aren't specified.

<form>
  <input type="text" name="fullName"
    pattern="w{2,16}sw{2,16}"
    placeholder="Full Name (Ex: John Doe)"
    autofocus
  />
  <input type="email" name="email"
    placeholder="Email address"
  />
  <input type="submit" value="Save" />
</form>

Normally, you'll want to have two separate fields in your forms when asking for a first and last name. However, asking for a full name in a single field makes the field a great candidate for a custom pattern attribute.

The pattern used to validate a full name in this case is pretty simple; we look that the input as a word between 2 and 16 word characters (letters, and in this case possibly even numbers), followed by a single white space, which is in turn followed by another word of length greater than two, but less than 16 characters.

A placeholder string is added to both input field elements to avoid the need for extra labels in the form. This way the form can be nice and concise, yet descriptive enough that the user is never confused about what the form is asking.

Data attributes

When you need to need to store data in an HTML element and there is no other attribute that would be more appropriate to hold that data, the HTML5 specification provides a special attribute for this very situation. Although the specification specifically refers to this attribute a custom data attribute, most people simply call them as the data attributes.

The way these custom data attributes work is very simple. Simply create the attribute name of your choice starting the name keyword with the prefix data-, then using any keyword of your choice that is at least one character in length. The only restriction is that the keyword must not contain any uppercase letters, although all HTML element attributes get lowercased automatically by default. You may add an arbitrary amount of such custom attributes to a single element. Finally, any custom data attributes may have any value of your choice, have the empty string as its value, or be empty, in either case the attribute is considered to have the value true (and the value false in its absence).

<!-- Indicates an element that display some sort of score -->
<input type="text" id="scoreDisplay"
  <!-- Indicates that this score is not yet a new high score -->
  data-is-high-score="false"
  <!-- Indicates the current high score -->
  data-score-to-beat="891,958"
  <!-- Not a good use of data attributes, since the disabledattribute is a better choice -->
  data-enabled="false"
/>

In the example code just seen, we have some DOM node that happens to be an input tag and represents the score for some game. The first two sample data attributes, data-is-high-score and data-score-to-beat, are good examples. Just by looking at the names chosen for each attribute, we can infer the context in which they were meant to be used.

The first attribute is meant to hold a Boolean value that represents whether or not the score displayed by the heading element is a new high score. Since it currently holds the value false, then obviously the current score is not yet a new high score.

The second attribute stores the current high score, meaning that if the player gets a score higher than that value, his or her score will become a new high score and the attribute data-is-high-score should be updated to hold the value true. Keep in mind that these attributes are static and meaningless and the logic of your application is in charge of adding meaning to them based on their context as well as handling any updates to them, such as the example described previously.

Finally, note the third data attribute example. This is not a very practical use of data attributes because there exists another HTML element attribute that exists for that very purpose, namely, to specify that an element is disabled.

To add, remove, and check for an element's attributes and their values programmatically, you can use the following JavaScript APIs:

var myInput = document.getElementById("scoreDisplay");

// Check for the presence of an attribute
if (myInput.getAttribute("data-is-high-score") == null) {

  // If attribute is not present, add it to the element with somedefault value
  myInput.setAttribute("data-is-high-score", false);
}

// If attribute is present, check its value
else {

  var isHighScore = myInput.getAttribute("data-is-high-score");

  if (isHighScore) {
    // Do something with this new high score
  } else {
    // The current score is not yet a new high score
  }
}

Used in the game

There were a couple of usages of custom data attributes in the game with different purposes and for different reasons. As mentioned previously, one use was to specify a player's current speed. Two other instances of the attribute were used to identify and distinguish a player from the other and to group separate buttons that were intended to behave the same way.

Note

While the official specification states that you should always use the most appropriate attribute to store data in a DOM element, you should also keep in mind that the line that separates a possible custom data attribute and some other existing attribute may at times become gray. When this happens, you should prioritize your specific needs and goals.

For example, if you are trying to use a custom data attribute to name a group of related elements, the question might arise that a simple CSS class can achieve the same result. Some people might argue that since CSS classes already exist and their purpose is to group related elements, others may also argue that if no specific style is shared among these elements, then use of such a custom data attribute is well justified. However, the overruling factor should be the specific application goals and needs, so if, for example, adding a symbolic CSS class to group these elements would make it confusing, since no real corresponding CSS class exists, then the use of the custom data attribute is indeed well justified.

<section class="tracks">
  <div class="track">
    <span data-name="badGuy" data-speed="0"></span>
  </div>

  <div class="track">
    <span data-name="goodGuy" data-speed="0"></span>
  </div>
</section>

Note that each span element inside the div.track element has both, a data attribute of name, which distinguishes the hero player from the enemy player, and a data attribute of speed, which specifies how much each element moves by on each tick of the game timer. Whether that number represents pixels, percentages, or any other unit is irrelevant, since both players have the value set to zero, meaning that they move nothing per timer cycle.

Whether the data attribute name could be better represented by a CSS class can be argued in either direction. In this case, I chose to use a data attribute because then the styling can be independent of anything, and that concern can be delegated to another part of the application without any hesitation.

<button data-intent="play">Play Again</button>
<section id="mainContainer">
  <div id="wordsToWrite"></div>
  <div id="wordsWritten"></div>
  <button data-intent="play">Play</button>
</section>

Here we have two separate buttons that share the same data attribute intent = "play". With that attribute present, and that value assigned, we can then some JavaScript logic to handle those, and any other buttons, making their behavior predictable and universal.

// Select all buttons with a custom data attribute of intent anda value of play
var playBtns = document.querySelectorAll("button[data-intent='play']");
// Assign the same click handler to all of these buttons
for (var i = 0, len = playBtns.length; i < len; i++) {
  playBtns[i].addEventListener("click", doOnPlayClicked);
}

// Now every button with data-intent="play" executes thisfunction when clicked
function  doOnPlayClicked(event) {
  event.preventDefault();

  // Play button click behavior goes here
}

Query selectors

There are two different, yet very similar, APIs as part of the new selectors interface. One selects a collection of elements that match the query used and the other only matches one. If multiple nodes are matched by a query used in the single selector version, only the first occurrence is returned.

To use this interface, you call the appropriate function on the document object and supply a string representing a CSS query. Now you can stop selecting an element by its ID, then navigating weird sub paths, in order to finally get to the element you want to target programmatically.

Note

Before this feature was available, it was common for developers to clutter their document structure with ID and class attributes just to make targeting those elements programmatically a bit easier. While using CSS expressions to target specific nodes may be easy enough that you may feel that you no longer need to add a unique ID or a class to an element just so it's easier to target that element through code, keep in mind that long CSS expressions might be so complex that the performance of your application might be compromised because of the time it takes to navigate to those elements. Remember that the shorter the CSS query, the easier it is for the browser to match the elements involved.

Consider the following code snippet from the game, where we try to register a click event listener to the image element found inside a navigation menu holding the game options:

<nav id="navOptions">
  <div>
    <p>Difficulty &raquo; <span>1</span></p>
    <input type="range" step="1" min="1" max="3" value="1" />
  </div>
  <img src="img/options-icon.png" />
</nav>

<script>
// 1. Capture the image element inside that nav structurewith id="navOptions"

// ----------------------------------
// Without query selectors:
// ----------------------------------
var nav = document.getElementById("navOptions");
var img = null;

// Iterate through every child node of nav instead ofdirectly targeting the current
// position of that image element in case the structureof #navOptions change,
// in which case this code wouldn't need to be updated.
for (var i = 0, len = nav.children.length; i < len; i++) {
  if (nav.children[i].tagName == "IMG") {
    img = nav.children[i];
    break;
  }
}

// -----------------------------------
// With the query selectors:
// -----------------------------------
var img = document.querySelector("#navOptions img");

// 2. Set the click handler
if (img) {
  img.addEventListener("click", doOnOptionsClicked);
}
</script>

You will note that the demonstration of the old way of selecting elements uses a very defensive programming style. While trivial selections may not need such paranoiac measures, a large application would definitely benefit from such an approach in case a particular element is not found in the DOM, and an event listener is attempted to be added to a variable holding a null reference. Either way, you can see how the new selectors API solves this problem in this particular situation, since no matter what other elements are possibly added to, or taken away from that #navOptions subtree, the CSS query used in the querySelector("#navOptions img") statement would still hold true, whereas nav.children[1] might not refer to the same element, should the structure of #navOptions change.

Also, you will note that the call to querySelector will return null if no elements are matched with the CSS query provided. When using the querySelectorAll interface, remember that a list will be returned whenever a match is found, whether one or more elements are selected. Thus, if only a single element is matched, you would still need to index into the result set in order to match the only element returned.

<div id="wordsWritten">
  <span class="correct">I</span>
  <span class="correct">love</span>
  <span class="correct">HTML5</span>
  <span class="wrong">?</span>
</div>

<script>
var correctWords = document.querySelectorAll("#wordsWritten .correct");
// correctWords == [
//  <span class="correct">I</span>,
//  <span class="correct">love</span>,
//  <span class="correct">HTML5</span>]

var wrongWords = document.querySelectorAll("#wordsWritten .wrong");
//  wrongWords == [
//    <span class="wrong">?</span>]
</script>

Used in the game

As mentioned previously, every node selection was done using query selectors in the game. It is worth mentioning that it is not possible to register an event listener to a collection of nodes at once. You will need to iterate through the entire list (or at least a part of it) in order to touch one or more individual nodes in the list.

// Select a collection of zero, one, or more buttons
var playBtns = document.querySelectorAll("button[data-intent='play']");

// Assign the same click handler to all of these buttons
for (var i = 0, len = playBtns.length; i < len; i++) {
  playBtns[i].addEventListener("click", doOnPlayClicked);
}

// This does not work >> TypeError: Object [object Array] hasno method 'addEventListener'
  playBtns.addEventListener("click", doOnPlayClicked);

If you attempt to call any function that would normally call on an individual node directly on a result set from a querySelectorAll call, you will get a TypeError since the function called is applied to the array element and not each and all of its elements.

Web fonts

The new web fonts API is particularly exciting and liberating to all those web developers out there who have had to rely on images in order to make the web truly beautiful up until now.

To use custom fonts, we use the CSS property @font-face and specify a few attributes, such as the name of the font and the font file, which the browser will follow and download to the client much like it does with assets such as images, videos, and sound files that are called by the client.

@font-face {
  font-family: "Lemon",
  src: url("/fonts/lemon.woff") format("woff");
}

h1 {
  font-family: "Lemon", Arial, sans-serif;
}

The only caveat with web fonts is that not all browsers support the same font types. The solution, though simple, can be a bit of a pain, since it involves uploading the different file format to your server then specifying each and all of them in the font-face declaration. When a browser comes across your custom font declaration, it can then download the file format that it can handle and serve that to the client.

@font-face {
  font-family: "Lemon",
  src:url("/fonts/lemon.woff") format("woff"),
      url("/fonts/lemon.eot") format("eot"),
      url("/fonts/lemon.ttf") format("truetype"),
      url("/fonts/lemon.svg#font") format("svg");
}

As of this writing, Google Chrome, Firefox 3.6, and Microsoft Internet Explorer 9 accept the .woff font files, while Safari, Opera, and Android support the .ttf files. Apple's iOS only supports the .svg font files.

Alternatively, you can encode the entire font file into a Data-URI string and embed that into your CSS.

@font-face {
  font-family: "Lemon";
  src: url("data:font/opentype;base64,d09GRgABAAAAA...");
}

Note

One great resource for free, open source, web fonts is Google's Web Fonts project. There you can find a directly with several hundred different font files that you can search from and import right into your projects. Each file is hosted on Google servers, which means that the availability of these fonts is very high and the delivery speed is Google fast. What's more, through their service, once you find a font that you'd like to import into your project, Google provides you with three options to import it: a standard link rel="stylesheet" tag, a CSS @import statement, or a JavaScript alternative. Either choice you make, the font file that eventually gets served to your end users is the exact format that the requesting browser supports. This way you don't need to specify the multiple src: url attributes in your CSS file.

Transitions

CSS transitions is a great and simple way to add that special effect to any existing website. It is likely that your existing projects already use some sort of state change to elements based on different events, such as a hover effect, which may cause elements to change size, color, or position.

By adding a CSS transition attribute to these elements, you can more closely control the various states between the original state and the final state. For example, if a link is set to have a blue color by default and the font color changes to purple when the user moves the mouse cursor over that text, a CSS transition would cause the text to smoothly and gradually change the blue into the purpose color, instead of simply changing the color property in the blink of an eye.

Remember, only properties that can possibly have intermediate states can transition between states. Normally, you can determine if that is the case with a particular attribute by looking at the value assigned to the attribute. If the value is a number, such as 10px, 2.5em, or 50%, then you can be sure that a transition property would result in an incremental change into the final state. Since colors are ultimately represented by numbers, whether they're hexadecimal values or something else, we are able to apply transition properties to colors as well.

#navOptions {
  position: relative;
  top: 10px;
  left: -230px;
  width: 325px;
  overflow: auto;
  padding: 10px;
  border-radius: 0 10px 10px 0;
  -webkit-transition: all 0.3s;
}

#navOptions.open {
  left: 0;
  background: rgba(100, 100, 100, 0.5);
  padding-right: 15px;
}

In this example, the element with the ID property of navOptions is given a transition attribute. By default, that element has a left position of -230px, a patting of 10px, and no background color. Then we define a class called open, and specifically associate it with the name #navOptions element. This class specify different values for the left, padding, and background properties. Thus, whenever the #navOptions element gets assigned to the class .open, those three properties will change gradually from the default into the new values.

Note that the transition property is assigned with a browser-specific prefix. This was done for simplicity, but in your production code you might want to check the status of each browser in regards to that specific property, and specify all values possibly needed, along with a plain, non-prefixed version for when the prefix is removed from a browser:

#navOptions {
  position: relative;
  top: 10px;
  left: -230px;
  width: 325px;
  overflow: auto;
  padding: 10px;
  border-radius: 0 10px 10px 0;

  -webkit-transition: all 0.3s; /* Webkit-based browsers */
  -moz-transition: all 0.3s;     /* Mozilla Firefox */
  -o-transition: all 0.3s;          /* Opera */
  transition: all 0.3s;              /* One day, every browser. Today, any browser not in experimental */
}

The example just seen uses short hand to define all four possible properties, but they can also be declared individually:

#navOptions {
  position: relative;
  top: 10px;
  left: -230px;
  width: 325px;
  overflow: auto;
  padding: 10px;
  border-radius: 0 10px 10px 0;

  transition-property: padding;
  transition-duration: 0.3s;
  transition-timing-function: linear;
  transition-delay: 1s;
}

In short hand, the order of these parameters are: property, duration, timing function, and delay. You can also specify multiple properties in the same declaration by using a comma-separated list of properties:

#navOptions {
  position: relative;
  top: 10px;
  left: -230px;
  width: 325px;
  overflow: auto;
  padding: 10px;
  border-radius: 0 10px 10px 0;

  transition: padding 0.3s ease-out 0.1s, left 0.5s linear,background ease-in 1s 1s;
}

Note that you can have any arbitrary number of properties specified, or simply use the keyword all. Also, as shown in the previous example, not all values need to be the same (each property can have a different duration, timing function, or delay). The default delay is 0 (meaning that the transition starts right away as soon as the property change is triggered), and the default value for the timing function is ease.

Animations

The animations API is somewhat similar to the transitions API, but the main difference is that we get to specify two or more keyframes and the browser transitions between these keyframes. A keyframe is simply a point in time, with a series of properties specified for that particular point.

To use a CSS animation, you'll first need to create a named keyframe sequence, specify all the properties for each keyframe, then assign that keyframe sequence to some element. Similar to transitions, when you specify the keyframe sequence to an element, you also specify the configurations for that sequence, such as animation name, duration, timing function, delay, iteration count (how many times to play the entire keyframe sequence), direction (whether the animation plays from the first keyframe to the last or from the last to the first), and the play state (indicating whether the animation is running or paused).

To set up a keyframe sequence, simply use the @keyframes keyword, followed by a string identifying that sequence.

@keyframes myAnimation {
}

Then, in a way slightly different from other CSS properties, we nest other expressions inside this declaration, where each sub-expression is an individual keyframe declaration. Since each keyframe is a point in time (where the total time is specify when the animation sequence is applied to an element, as we'll see shortly), we specify each keyframe in one of two ways: we can either specify a percentage of the time for when a keyframe is called into action, or we can use the keywords from and to, indicating the point in time when 0 percent and 100 percent of the total animation time has elapsed.

@keyframes myAnimation {
  from {
    background: #ffffff;
  }

  to {
    background: #000000;
  }
}

Note that the from keyword behaves the exact same way as 0 percent and the to keyword the same as 100 percent. Whether to use one over the other is purely a matter of preference.

@keyframes myAnimation {
  0% {
    left: 0px;
    top: 0px;
  }

  25% {
    left: 0px;
    top: 50%;
  }

  50% {
    left: 50px;
    top: 100%;
  }

  75% {
    left: 50px;
    top: 100%;
  }

  100% {
    left: 0px;
    top: 0px;
  }
}

Needless to say, the same issues regarding vendor prefixes apply to the animations interface.

-webkit-@keyframes myAnimation {
  from {
    background: #ffffff;
  }

  to {
    background: #000000;
  }
}

#sky {
  -webkit-animation-name: myAnimation; 
  /* This is how you link a keyframe sequence to an element */
  -webkit-animation-duration: 3s; 
  /* Can be a value in seconds (s) or milliseconds (m) */
  -webkit-animation-timing-function: ease-out; 
  /* Can be linear, ease, ease-in, or ease-out */
  -webkit-animation-iteration-count: 23; 
  /* Can be any non-negative integer or "infinite" */
  -webkit-animation-direction: alternate; 
  /* Default is "normal" */
  -webkit-animation-play-state: running; 
  /* Can also be "paused" */
}

The text shadow

The text shadow interface is much simpler to use than the transition or animation APIs since it only has four basic parameters, but can be equally as powerful in adding beautiful visual elements to make the user experience great. The parameters are the horizontal and vertical offset of the shadow relative to where the text is, the amount of blur to apply to the shadow, and finally, the color of the shadow, which can have the optional alpha channel for added opacity.

h1 {
  text-shadow: -5px 5px 0 #000;
}

Multiply shadows may be added to the same element by adding them in a comma-separated listed:

h1 {
  text-shadow: -5px 5px 0 #000, 5px -5px 0 rgba(50, 50, 50, 0.3);
}

Also, text shadows may be added to custom fonts embedded onto the page through HTML5's web fonts:

h1 {
  text-shadow: 1px 1px 5px #000;
  font-family: "Lemon";
}

The box shadow

Box shadows are identical to text shadow, except for a few very important distinctions. First and for most, they are not applied to text but only to box elements. You could in fact apply a box-shadow property to a text element (such as a p tag, h1, h2, h3, and so on), but the effect would be drastically different. While the text shadow effect, essentially, simply renders an offset and blurred copy of the text to which the shadow is applied, a box shadow effect is simply a copy of the rectangle created by the elements width, height, margin, and border which is rendered with the specified color, offset, and blur values assigned in CSS.

div {
  box-shadow: 5px 5px 3px #aaa;
}

Again, just like with text shadows, we can apply multiple box shadows to the same element through a comma-separated list of shadow declarations.

div {
  box-shadow: 5px 5px 3px #aaa, -10px -10px 30px rgba(255, 255, 255, 0.01);
}

If you apply multiple shadows as just shown, any subsequent shadows should be drawn behind shadows drawn earlier, should they so happen to overlap. For example, the following set of shadows would display as a single, red shadow, since the red (#cc0000) was declared first and they both just so happen to cover the same area. Should the shadows have any amount of blur, the effect would be a mixture of the shadows. Since in this particular example, the shadows are completely solid, no blending takes place and the shadow in front takes precedence (since it's drawn higher in the rendering stack).

div {
  box-shadow: 5px 5px 0 #cc0000, 5px 5px 0 #0000cc;
}

There is also a fourth value that can be specified in a box shadow, which specifies the spread (or size) of the shadow. The default value is zero, which means the blur will begin right at the edge of the container created by the containing element. The effect created by a shadow spread is similar to a border placed between the blur of the shadow and the container created by the containing element.

Finally, the optional inset keyword tells the browser to draw the shadow from the border of the container inwards, as opposed to from the border (or where the border would be, had there been a border width greater than zero) outwards in the direction of the horizontal and vertical offsets.

div {
  box-shadow: inset 5px 5px 3px #aaa;
}

Note that in a multiple shadow declaration, each shadow can specify its own rendering orientation.

div {
  box-shadow: inset 5px 5px 3px #aaa, 
  /* This shadow is drawn inside the div */
    5px 5px 3px #aaa; /* And this shadow is drawn outside it */
}

The border radius

The border radius property allows us to round the corners of the container formed by an element's dimensions. If there is any content where the rounding of the corner reduces the physical area of the container, that content is not drawn. Finally, the border radius declaration can be specified by a single value, where that value is applied to all corners (observe that here we refer to corners, not sides, as in a border declaration), by supplying four different values (where the corners would be targeted in the order top-left, top-right, bottom-right, and bottom-left), or by targeting each corner individually.

div.one {
  border-radius: 5px; /* Make all four corners round by 5px */
}

div.two {
  border-radius: 5px 10px 
  /* Top left and bottom right = 5px, top right andbottom left = 10px */

div.three {
  border-top-left-radius: 4px;
  border-top-right-radius: 8px;
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 16px;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57