The Modern Web with HTML5, CSS3 and JS

The modern coding methods and techniques that you can use to build websites that work across multiple devices or that are tailored to the single device class you’re targeting

Peter Gasston

266 Pages

29440 Reads



PDF Format

8.22 MB

HTML Learning

Download PDF format

  • Peter Gasston   
  • 266 Pages   
  • 26 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    read more..

  • Page - 4

    read more..

  • Page - 5

    read more..

  • Page - 6

    read more..

  • Page - 7

    read more..

  • Page - 8

    read more..

  • Page - 9

    read more..

  • Page - 10

    read more..

  • Page - 11

    read more..

  • Page - 12

    read more..

  • Page - 13

    read more..

  • Page - 14

    read more..

  • Page - 15

    read more..

  • Page - 16

    read more..

  • Page - 17

    read more..

  • Page - 18

    read more..

  • Page - 19

    read more..

  • Page - 20

    Introduction 3 But desktop computer use is on the wane as many people nowadays, especially home users, tend toward mobile or tablet devices (which I’ll come to shortly). In the last quarter of 2012, global PC shipments were down almost 5 percent from the previous year. That said, research shows that people still tend to use read more..

  • Page - 21

    4 Introduction smartphone sales were estimated to account for 27 percent of the global market; at the end of 2012, estimates were that 1 billion smartphones were in use, with that number predicted to double by 2015. The sheer variety of mobiles and mobile browsers in the global mar- ket means that I’m selective about the coverage read more..

  • Page - 22

    Introduction 5 Tablet Tablet computers have been around for years, but it wasn’t until Apple came along with the iPad in 2010 that they became more of a leisure item than a desktop accessory. Many other devices have followed the iPad, with Android-based tablets doing especially well in the mid-sized 7" range and Microsoft read more..

  • Page - 23

    6 Introduction The emerging common behavior is for web TVs to be used for video and interactive services, with a real-time social aspect happening concur- rently on the user’s mobile or tablet. Recent research shows that 77 percent of people use another screen while watching (if that’s the right word) TV, and of that figure, only 5 read more..

  • Page - 24

    Introduction 7 runs a full version of the Linux desktop. The PadFone by Asus is a phone that turns into a tablet when docked with a larger touchscreen. Your TV becomes a media center when you plug Apple TV or Roku into it. This change is set to outdate all of our existing terminology. In the foreseeable future, the word tablet read more..

  • Page - 25

    8 Introduction There’s also the issue of size. The presumption is that for a large-screen device like a TV, viewers want a richer graphical environment, but a large screen doesn’t equal a powerful processor or a fast connection. Many web- enabled TVs have processors no more powerful than a smartphone, and the connection speed is open read more..

  • Page - 26

    Introduction 9 Your site needs to be fast—and feel fast—regardless of the device it’s being displayed on. And fast means not only technical performance (which is incredibly important) but also the responsiveness of the interface and how easily users can navigate the site and find what they need to complete the task that brought them to read more..

  • Page - 27

    10 Introduction Further Reading Statistics used in this chapter were taken from many sources, nota- bly Vision Mobile’s “The Mobile Industry in Numbers” at http://www and Cisco’s “The Internet of Things” at the-internet-of-things-infographic/. You can find a good read more..

  • Page - 28

    1 T H E W E B PL A T FOR M In this chapter, I’m going to talk about the web technologies that you’ll learn in this book, the knowledge you’ll need to get the most from reading it, and the demands and requirements of working on the multi-device Web. This chapter is about making sure we’re on the same page, figuratively read more..

  • Page - 29

    12 Chapter 1 A Quick Note About Terminology Throughout the book, I refer quite often to building websites or sites, but this terminology is just convenient shorthand to avoid repetition. The fea- tures you’ll learn from this book are relevant to websites, web applications, packaged HTML hybrid applications—in short, anything that can use read more..

  • Page - 30

    The Web Platform 13 Figure 1-1: A Hello World message logged in the console in Firebug If you’re still reading this, either you have all the knowledge required to proceed, or you’re getting ready to try to bluff your way through. Regardless, let’s move on to talk about technology. Getting Our Terms Straight There’s some confusion over read more..

  • Page - 31

    14 Chapter 1 New features in HTML5 include ways to structure documents for pro- viding meaning and accessibility; I cover this in Chapter 2. HTML5 also has a whole range of new form functionality and UI controls that make it easier to build applications, which we’ll look at in Chapter 8. And HTML5 read more..

  • Page - 32

    The Web Platform 15 for compatibility with legacy pages on the Web; standards mode is for modern, standards-compliant behavior; and almost standards mode is standards mode with a few quirks. To know which mode to use, the browser looks to the Doctype. You always want to use standards mode, so the Doctype in HTML5 is read more..

  • Page - 33

    16 Chapter 1 The only time you need to use the tags is when you’re not using default CSS or JavaScript; for example, some releases of Firefox have experimental implementations of recent versions of JavaScript, and for safety’s sake they require that you include a flag on the type attribute if you want to use it: <script read more..

  • Page - 34

    The Web Platform 17 traversal for styling much easier, and more dynamic effects such as two- and three-dimensional transitions and transitional animations (you can read more about these in The Book of CSS3, by this author, from this publisher). But beyond the many glittery visual effects, the real revolution of CSS3 has come through media read more..

  • Page - 35

    18 Chapter 1 CSS Frameworks and Preprocessors Nowadays using a helping hand with CSS development is pretty de rigueur, especially when working on large development teams and/or on large proj- ects. Usually these helpers come in the form of frameworks or preprocessors and quite often both. A framework is a set of predefined CSS rules that read more..

  • Page - 36

    The Web Platform 19 The HTML5 Test is a site that tells you how many features from the HTML5 spec your browser supports, but also very usefully keeps records of implementation levels across many different browsers and devices, including TV and games console browsers, and also allows you to do side- by-side comparisons of up read more..

  • Page - 37

    20 Chapter 1 Summary This chapter provided you with all the information you need to get started in modern web development. I disambiguated the common meaning of HTML5 and introduced you to the web platform. You learned what HTML5 is useful for and how to start writing it, and you also had a brief introduc- tion to CSS3. The read more..

  • Page - 38

    2 S T RUC T UR E A N D SE M A N T I CS Remember the parable about the man who built his house on sand? Or the pigs who made their houses out of straw and sticks? Losers. They lost because they didn’t put enough value on the importance of structure. To make good sites you need good structure, and on the Web that starts read more..

  • Page - 39

    22 Chapter 2 HTML5 and related technologies make all of this easy. Using existing and well-implemented methods, you can create pages that are solid, mean- ingful, high performing, and rich in data. New Elements in HTML5 One of the major new features in HTML5 is a range of new semantic ele- ments, extending the suite far read more..

  • Page - 40

    Structure and Semantics 23 HTML5 has other new elements that don’t affect the basic structure of a page; I’ll cover them where necessary throughout the rest of this book. For now, let’s look further into the reason these new elements were created in the first place. What’s the Point? The stated aim of these new elements read more..

  • Page - 41

    24 Chapter 2 <article> <h1>Eastern Gorilla</h1> ... </article> <article> <h1>Western Gorilla</h1> ... </article> </section> <section> <h1>Orangutan</h1> ... </section> The resulting outline would be the same as in the HTML4 example because each section or read more..

  • Page - 42

    Structure and Semantics 25 Start <article> <aside> <figure> <div> <section> Appropriate element e.g. in a feed reader Sidebar, comments section, pullquote, glossary, advertising, footnote etc that’s tangentially related to the page or content… One or more images, graphics, code samples etc, plus optional <figcaption> … html5doctor gure read more..

  • Page - 43

    26 Chapter 2 On top of that, no currently available browsers support the new outlin- ing algorithm (the JAWS screen reader does, albeit with bugs), so all your hard work doesn’t really have much benefit—this is likely to change in the future, of course. In the end, the decision to use the new structural elements is, of course, up read more..

  • Page - 44

    Structure and Semantics 27 Landmark roles are applied using the role attribute with a series of predefined values. These values do not directly correspond to the HTML5 structural elements, but they mostly match very well. For example, if you want to define the document area that contains general information about the site, such read more..

  • Page - 45

    28 Chapter 2 The Importance of Semantic Markup Before moving on to look at different ways of adding deeper rich meaning to your pages, let’s pause to ask the question, “Why bother with semantics at all?” I mean, is something intrinsically wrong with marking up a page using mostly div elements (as in the following code block)? read more..

  • Page - 46

    Structure and Semantics 29 Now you clearly know which header is important and what the main body content is. You’ve given the content some aboutness. As well as using semantic elements correctly to mark up your content, you can increase the meaning of your documents for machines rather than users (commonly known as structured data) read more..

  • Page - 47

    30 Chapter 2 Those few standardized class names have given much more meaning to this content for machines that are programmed to find it; a crawler that recognizes the hCard pattern will see the vcard class and know that the con- tent inside contains the information it’s looking for: It knows the first link contains the full name (fn) read more..

  • Page - 48

    Structure and Semantics 31 What the reader sees is the content of the element; what the machine sees is the value of the attribute. It means extra markup, but everybody’s happy. As with microformats, some search engines look for common RDFa patterns to improve their search results. I’ll go into this in more detail in “Rich read more..

  • Page - 49

    32 Chapter 2 And, as with RDFa, you can describe content with predefined schema by linking to it with the itemtype attribute: <p itemscope itemtype="">My birthday this year is on <span itemprop="birthday" datetime="2013-12-14">December 14</span>.</p> You can use schema such as the previously mentioned Dublin read more..

  • Page - 50

    Structure and Semantics 33 microdata is that it’s capable of accommodating both of its contemporaries within its own flexible syntax. For example, here’s how to mark up hCard using microdata: <div itemscope itemtype=""> <p><a href="" itemprop="url fn">Peter Gasston</a> writes for read more..

  • Page - 51

    34 Chapter 2 Although my markup has gotten more complex, it means more now. Each of the vocabularies I’ve used is defined with a link to the relevant schema in the itemtype attribute, and the items are marked up with preset itemprop values. What’s interesting about is the way that specific schema inherit properties read more..

  • Page - 52

    Structure and Semantics 35 Data Attributes A further way that HTML5 extends the meaning that elements have is through the use of data attributes. These are user-defined attributes, the values of which are intended to provide information related to an ele- ment but without giving any extra semantic meaning to either machines or humans. read more..

  • Page - 53

    36 Chapter 2 In this example, I perform three operations: first getting the id data, then setting it to 100, then getting it again, and each time logging the results into the console. The resulting output is shown in Figure 2-5. Figure 2-5: Showing the results of data attribute manipulation with the API in the console jQuery and Data read more..

  • Page - 54

    Structure and Semantics 37 Figure 2-6: Finding the type of the results using the jQuery data() method with data attributes Data Attributes in the Wild Data attributes are so useful that some companies already take extensive advantage of them. Twitter was quick to adopt them, allowing them to be used as an option for adding a read more..

  • Page - 55

    38 Chapter 2 content probably means you want to add lots of semantic richness in order to get the most from search engines and crawlers. In this case, you’ll want to consider RDFa, microformats, and/or microdata. Building a hybrid app for mobile devices, however, will make that much less of a consideration. Further Reading HTML5 Doctor read more..

  • Page - 56

    3 DE V ICE -R E S P O NSI V E CS S With a solid structure in place, the next step is to plan how you’re going to display your content. You have many differ- ent approaches and methodologies to choose from. Among the development community’s chat- tering classes, two of the most popular methods of building websites today are adaptive or read more..

  • Page - 57

    40 Chapter 3 Media Queries In my opinion, media queries are the biggest agent of change in website design for many years—probably since CSS itself became mainstream. The widespread adoption of CSS allowed you to leave behind the rigid limita- tions of table-based websites, and media queries take that a step further, let- ting you style pages in read more..

  • Page - 58

    Device-Responsive CSS 41 So now that you know how media queries work and how to include them in your pages, let’s move on to explore the media features themselves— starting with the most common, those that use the dimensions of your device or browser viewport. Media Features Based on Dimensions Media queries are most commonly used today read more..

  • Page - 59

    42 Chapter 3 Many media features, including width, allow the prefixes max- and min- before the feature name. These stand for maximum and minimum respec- tively, which you probably don’t need me to explain, and in practice mean “no more than” and “no less than.” For example, using max-width you can apply style rules to any browser that read more..

  • Page - 60

    Device-Responsive CSS 43 Now, I’m sure it doesn’t take much imagination on your part to see how the width feature could be useful: You could use smaller text on smaller screens and larger text on larger screens, for example: @media screen and (max-width: 480px) { h1 { font-size: 2em; } } @media screen and (min-width: 481px) { h1 { read more..

  • Page - 61

    44 Chapter 3 A quick way to work out which aspect ratios are greater than others is to divide the first figure by the second; a 4/3 ratio works out to 1.333, whereas 8/5 works out to 1.6. The larger the result, the wider the ratio. The example shown here applies only to screens for which that number is 1.6 or more. Probably more read more..

  • Page - 62

    Device-Responsive CSS 45 grips with how they work. Zoe Mickley Gillenwater wrote an excellent post on the topic, Essential Considerations for Crafting Quality Media Queries, in which she says: Designing web layouts with media queries is a process. You need to keep them in mind from the very beginning and make decisions at several points about read more..

  • Page - 63

    46 Chapter 3 The ratio of virtual pixels to physical pixels is known as the device pixel ratio. I’ll use the abbreviation DPR for this, although it is also known as DPPX (dots per pixel). Devices that don’t have DIPs have a DPR of 1—that is, one virtual pixel to one physical pixel. The most common high-resolution devices as I read more..

  • Page - 64

    Device-Responsive CSS 47 In fact, two media features are available. The first, and most widely used owing to WebKit’s popularity on mobile devices, is a proprietary fea- ture called -webkit-device-pixel-ratio. This feature—along with the related max- and min- prefixes—lets you target a device’s DPR. For example, here’s how to add a read more..

  • Page - 65

    48 Chapter 3 a little extra logic. As previously mentioned, using a comma-separated list of media queries means the rules are applied if any one of them is true: @media screen and (min-resolution: 2dppx), screen and (-webkit-min-device-resolution: 2) { E { background-image: url('foo-hires.png'); } } This logic tests that the device has a DPR read more..

  • Page - 66

    Device-Responsive CSS 49 The solution that Apple came up with when they created Safari for iPhone was to ask developers to add a special tag, known as the viewport meta tag, in the head of their documents. This tag is used to control the dimensions and scaling of the browser viewport. Here’s an example: <meta name="viewport" read more..

  • Page - 67

    50 Chapter 3 The reason this solution is more useful is that you can combine @viewport with media queries to have different viewport parameters, depending on the viewing device. Consider this example: @media screen and (max-width: 480px) { @viewport { width: 480px; } } @media screen and (min-width: 481px) { @viewport { read more..

  • Page - 68

    Device-Responsive CSS 51 this, a hover feature is available for testing the existence of a hover state in the device. As the hover query is Boolean, no second value is required: @media screen and (hover) {} If you want to set rules on devices that don’t have a hover state, you could use either the 0 value or the not operator, read more..

  • Page - 69

    52 Chapter 3 The matchMedia() method is used to run the queries, which are provided in a string as an argument. Try running this in your developer console: window.matchMedia('screen and (min-width: 800px)'); The result of this code is a MediaQueryList object, and how it appears in your console depends on the browser and tools you use; read more..

  • Page - 70

    Device-Responsive CSS 53 In the example file mq-widthwatch.html, you can see the results of a script based on this; it returns the same results as in the previous example, but you won’t need to refresh the page to get a different result; just resize the window. Adaptive vs. Responsive Web Design As mentioned at the start of this chapter, read more..

  • Page - 71

    54 Chapter 3 Maybe you can already see the problem. As you know, the CSS box model makes padding, borders, and margins extra to the content’s dimen- sions, so now these elements have a combined width of 100 percent, plus 40px, making them wider than their container. A further problem when using percentage widths is that nesting elements leads read more..

  • Page - 72

    Device-Responsive CSS 55 Some people find box-sizing so handy that they advocate applying it to every element, using the universal selector: * { box-sizing: border-box; } I think this is overkill and could cause unwanted difficulties, so my pre- ferred approach is to apply it only where it’s actually required: div, .etc { box-sizing: read more..

  • Page - 73

    56 Chapter 3 margin: 0 20px; padding: 0 1em; width: calc(50% - calc(48px + 2em)); } You’re not limited to using calc() only for width or height properties, however; you can use it on any property or function where length values are permitted. Viewport-Relative Length Units As mentioned previously, one problem with using percentages read more..

  • Page - 74

    Device-Responsive CSS 57 Where rem differs from em is that the latter is inherited, whereas the former is fixed. For example, say you set a font size of 10px on the root of a document: html { font-size: 10px; } If you want to make a p element that’s 12px in size, you could use either one of them in this way: p read more..

  • Page - 75

    58 Chapter 3 The mobile first methodology targets the smaller (and most probably lower-powered) devices first and then adds layers of complexity to accom- modate larger devices. What this means in essence is you start with a set of styles that’s served to all devices—such as color, typography, iconography, and so on—as well as read more..

  • Page - 76

    Device-Responsive CSS 59 What this means in practice is using media queries to change content, not when an arbitrary device size has been reached, but when that content becomes awkward. To illustrate what I mean, imagine I have a stylesheet applied to wide viewports using a media query: <link rel="stylesheet" href="foo.css" read more..

  • Page - 77

    60 Chapter 3 Resizing most objects with percentages (or viewport-relative units if you go that way) is not a problem; you could quite simply set the max-width property to 100 percent to prevent the object ever being wider than its container: img { height: auto; max-width: 100%; } Notice that I also set the auto value on the height read more..

  • Page - 78

    Device-Responsive CSS 61 obviously doesn’t look great; the element in the middle, #obj-contain, has kept its original aspect ratio but been resized so the entire img fits inside its parent, causing the “letterboxing” effect; finally, #obj-cover has also kept its aspect ratio but been resized so the whole of its parent is covered. To read more..

  • Page - 79

    62 Chapter 3 Figure 3-7: Different values for the object-position property The Image Problem Although you’ve seen that resizing and positioning objects using respon- sive techniques is quite straightforward, images are still a source of major problems in responsive design for a number of reasons. Chief among them is the question of file size; read more..

  • Page - 80

    Device-Responsive CSS 63 WA R N I N G Remember this suggestion is only the most prominent as I write this; it may not be the final syntax. So this syntax allows for testing device resolution, but what about other media queries? You can add those with further source elements: <picture alt="Description of image subject."> <source read more..

  • Page - 81

    64 Chapter 3 article “A Pixel Is Not a Pixel Is Not a Pixel”: blog/archives/2010/04/a_pixel_is_not.html. Wikipedia has a list of com- mon device resolutions and pixel density: List_of_displays_by_pixel_density. Patrick Lauke wrote an article about user-controlled DPR, “device- PixelRatio in Opera Mobile”: read more..

  • Page - 82

    4 NE W A P P R O A CHE S TO CSS L A Y O U T S Once your markup is in place and you’ve considered how to best optimize your web- site or application for the devices they’ll be used on, you can actually start to create the layout of your website or application. Layouts have been quite limited and formulaic using the features read more..

  • Page - 83

    66 Chapter 4 WA R N I N G Although many of the new features in this chapter have already been implemented in browsers, they should be considered experimental and subject to change until the W3C has finished the standardization process. Detailed information on current browser support is in Appendix A and will be updated on read more..

  • Page - 84

    New Approaches to CSS Layouts 67 Figure 4-1 shows a comparison of the two approaches. The upper example uses column-count to create three equal columns that fill the par- ent’s width; the lower example has a column-width value of 120px, but the actual width of the columns is slightly different as each has been resized to better fit read more..

  • Page - 85

    68 Chapter 4 You can also add lines between each column, known as rules, with the column-rule property. The effect is essentially the same as the border property from CSS2.1, and it requires the same three values—one for width, one for style, and one for color—but it applies only to a single vertical rule, not to all four sides. read more..

  • Page - 86

    New Approaches to CSS Layouts 69 Figure 4-3: The second subheading spans all the columns, interrupting the content’s flow. I’ll use break-before as an illustration. The values you can apply to this property (and its siblings) set whether a column break occurs before an ele- ment. A value of column forces a break before the element read more..

  • Page - 87

    70 Chapter 4 The break-after and break-inside properties work the same way, except for the location where the break occurs. (Do you need me to tell you where that is, or would you like to guess?) Flexbox If you’re building more of an app than a content-rich website, especially if you’re building an app with lots of buttons read more..

  • Page - 88

    New Approaches to CSS Layouts 71 Figure 4-5: Child items of a flex container are automatically laid out horizontally. You can alter this direction by using the flex-direction property on the container. Its default value is row, which gives the behavior just discussed, whereas a value of column lays the items perpendicular to the direction of read more..

  • Page - 89

    72 Chapter 4 Figure 4-6: The row-reverse value quickly reverses the order of flex children. By using the flex-order property, you can go beyond this reverse order- ing to make completely bespoke ordering patterns. This property is applied to the flex items, not the container, and the value is a number that creates an ordinal group, so read more..

  • Page - 90

    New Approaches to CSS Layouts 73 Alignment Inside the Container Flex items with explicit dimensions might be smaller than their container, but one of the other benefits of Flexbox is tight control over alignment and placing. Before getting into this fully, I’ll quickly explain the two different axes used for alignment. The main axis goes in read more..

  • Page - 91

    74 Chapter 4 Have a look at flexbox-alignment.html and try changing the value of justify-content to see its effect. Figure 4-8 shows a few different values for comparison. Figure 4-8: Different values for the justify-content property: flex-start (top), center (middle), and space-around (bottom) But what about alignment on the cross axis? After all, read more..

  • Page - 92

    New Approaches to CSS Layouts 75 To control the alignment of individual items, use the align-self prop- erty. This property applies to the item, not the container, but the values are the same as align-items, and they have the same effects (although on the selected item only—sibling items remain unaffected). Adding Some Flexibility You’ve read more..

  • Page - 93

    76 Chapter 4 For example, Figure 4-10 shows the effect of a change to flex-grow; in the upper example, all items have an equal value of 1; in the lower example, item B has a value of 3, meaning it grows proportionally larger. Figure 4-10: A greater flex-grow value means item B in the lower example becomes proportionally larger than read more..

  • Page - 94

    New Approaches to CSS Layouts 77 The wrap value makes new lines below the first (or to the right in column view), but an alternative value of wrap-reverse changes the direction of the cross axis so new lines appear above (or to the left) instead. Figure 4-11 compares the two different values. Figure 4-11: Comparing values for the flex-wrap read more..

  • Page - 95

    78 Chapter 4 Although you can create entire page layouts with Flexbox, that’s not really what it’s intended for, and you would probably be hacking it around to get the exact layout you want. A better option is to use a dedicated set of page layout properties, and that’s where the Grid Layout module comes in. Grid Layout Grids read more..

  • Page - 96

    New Approaches to CSS Layouts 79 Grid track (column) Grid track (row) Grid element Grid area Grid line Grid item Figure 4-13: A simple 3×3 grid showing t he core terms used in the CSS Grid Layout syntax Declaring and Defining the Grid The first step in creating a grid is to declare the grid element. As explained in the introduction to this read more..

  • Page - 97

    80 Chapter 4 But fractions really come into their own when mixed with other units. For example, say you want to have one fixed-width column and two equal and dynamic columns as part of a responsive layout. Using fr is perfect for this. In the following code, three columns are created: one at 15em wide and the remaining two at read more..

  • Page - 98

    New Approaches to CSS Layouts 81 Repeating Grid Lines The simple grids defined in this chapter so far are good for learning and for some real-world situations, but you’ll often want to use quite com- plex grids for finer control over content. A 12- or 16-column grid is fairly common place, and each of those columns usually has a read more..

  • Page - 99

    82 Chapter 4 Figure 4-15: An item placed on the grid in the second column, second row (grid lines added for clarity) Figure 4-16: An item placed on the grid in the second column, first row (grid lines added for clarity) By default, the item is sized into the nominated cell, but you can expand the item’s size by making it span read more..

  • Page - 100

    New Approaches to CSS Layouts 83 Remember, you don’t need to define grid-column and grid-row in this instance, as they both default to 1. The item is placed in the first column of the first row—right where you want it—and it spans all three rows, as shown in Figure 4-17. Figure 4-17: An item on the grid spanning three read more..

  • Page - 101

    84 Chapter 4 Figure 4-18: Each item is aligned differently within its cell with the grid-row-align property. As you’re placing items into the grid, you may find that items overlap in the same cell. By default, items are stacked in DOM order, with items that appear later in the DOM stacked on top of items that appear earlier, as read more..

  • Page - 102

    New Approaches to CSS Layouts 85 still exist as shorthands: grid-column is shorthand for grid-column-position and grid-column-span, and grid-row is shorthand for grid-row-position and grid-row-span. That makes more sense than it might seem to at first. Other shorthands include the following: grid-position is shorthand for grid-column-position and read more..

  • Page - 103

    86 Chapter 4 To make multiple rows, add more strings, and make cells span rows and columns, add an extra instance of the letter in the direction you want to span. For example, in the following code, cell a will span two rows, and cell b will span two columns. I’ve formatted the strings to make it easier for you read more..

  • Page - 104

    New Approaches to CSS Layouts 87 Further Reading The ever-dependable MozDev has a really clear introduction to multiple columns, “Using CSS multi-column layouts,” at en-US/docs/CSS/Using_CSS_multi-column_layouts/. The Flexbox syntax has changed so often that almost every current online resource is out-of-date! That said, I recommend read more..

  • Page - 105

    read more..

  • Page - 106

    5 MODE R N J A V A S C R I P T The third column of front-end web devel- opment, along with markup and style, is behavior, which on the Web is performed by JavaScript. The activity around HTML5 and its related APIs has also brought many new features and (dare I say it?) improvements to this scripting language, making JavaScript both read more..

  • Page - 107

    90 Chapter 5 New in JavaScript From many new ways of DOM traversal to a whole new range of events, JavaScript has changed plenty in the past three or four years. If you don’t actively follow or keep up with the JavaScript community, you can easily miss it. In this section, I run through some of the new features of read more..

  • Page - 108

    Modern JavaScript 91 deferred execution, where the scripts are loaded without pausing the parser and then executed when the DOM is ready. In the final row, the parser still isn’t paused while the script is loading, but it is paused as it then executes. HTML parsing Script loading Script executing <script> <script defer> <script async> read more..

  • Page - 109

    92 Chapter 5 Even at this basic level, addEventListener() is useful enough, but it’s even more valuable than it might seem, as you can use it to add multiple events of the same type to an element. This means you can use scripts from dif- ferent sources without worrying about accidentally overwriting an event listener. The next read more..

  • Page - 110

    Modern JavaScript 93 Figure 5-2: Some of the information contained in the object created by a click event The event object is also useful when you want to stop a default action from occurring on an element. For example, you may attach an event to an a element that contains a link, but you don’t want the browser to read more..

  • Page - 111

    94 Chapter 5 You can remove anonymous functions from event handlers, but these methods are being deprecated in the latest revisions of JavaScript, so steer- ing clear of them is best. The DOMContentLoaded Event The old way to initiate scripts when a page had finished loading was to use the load event, but this method had the drawback of only read more..

  • Page - 112

    Modern JavaScript 95 Touch Events The Touch Events Level 1 specification has four events: touchstart fires when a finger (the word I’ll use from now on to avoid repeating the word “sausage”) to uches the screen. touchend fires when the finger is removed from the screen. touchmove fires when a finger moves between two points on the read more..

  • Page - 113

    96 Chapter 5 When fired, each event creates a pointerEvent interface that combines properties from the MouseEvent interface—currentTarget, coordinates where the event occurred, and so on—with a series of new properties, including the type of pointer used (pointerType), the amount of pressure applied, and the pointer’s tilt (where relevant). Without an read more..

  • Page - 114

    Modern JavaScript 97 A proposal to resolve this problem is a pair of similar methods called find() and findAll(), which would work in basically the same way but allow selectors relative to the target. To create a valid version of the previous code, use this: var foo = el.findAll('+ h2'); Although these aren’t really vital methods, they make read more..

  • Page - 115

    98 Chapter 5 } else { el.classList.add('foo'); } A quicker way to do this is with the toggle() method; toggle() simply removes a class if it’s present or adds it if it’s not: el.classList.toggle('foo'); JavaScript Libraries JavaScript libraries are collections of prewritten scripts that aim to reduce the cost of developing applications, and in read more..

  • Page - 116

    Modern JavaScript 99 jQuery is a JavaScript framework that simplifies the way you write scripts, abstracting common functions and providing a unified experience across all browsers. It works by creating a set of methods that require simple argu- ments from the author but perform some quite complex tasks. Here’s a simple example, which I’ll read more..

  • Page - 117

    100 Chapter 5 jQuery has a companion called jQuery Mobile, which might at first sound like a mobile-optimized version of the library, but it’s not that simple; jQuery Mobile is actually an extension to jQuery that provides cross-platform widgets and styles, as well as new events and methods that take advantage of the new capabilities read more..

  • Page - 118

    Modern JavaScript 101 both: 'foobar.css', callback: function () { ... } }); Here I’m running the same test as before but now loading bar.js if test is true, foo.js if it’s false, and foobar.css regardless of the result. When the test has finished, the anonymous function runs. Any test that returns a result of true or false can read more..

  • Page - 119

    102 Chapter 5 Yes, it uses YepNope.js as a basis. All the properties of YepNope can be used in Modernizr. You can use Modernizr.load() alone, or, if you’re using YepNope already, use the Modernizr object as the test: yepnope({ test: Modernizr.flexbox, nope: 'foo.js' }); Both work the same way. Your preference depends on your read more..

  • Page - 120

    Modern JavaScript 103 second argument of the method—in this case, view. The final output will be the text 'The Bonobo is funny.', which you can see in Example 1 in the file mustache.html. Using Mustache you can easily create sections of content that repeat— known, cleverly, as sections. Sections are useful for, for example, cutting read more..

  • Page - 121

    104 Chapter 5 This example may look complicated because of the script required for getting the external data with an XMLHttpRequest; if you prefer to use jQuery, you could get the same result in fewer lines of code: $.getJSON('json/apes.json', function (view) { var templApe = '{{#apes}}The {{name}} is funny.{{/apes}}'; var output = read more..

  • Page - 122

    Modern JavaScript 105 The idea behind a polyfill is that it happens invisibly; other than includ- ing a link to the polyfill file, no (or very little) more should be required from the author. In the case of multi-columns, the CSS to create the columns should be all you need. Of course, multi-columns create a dependency on JavaScript read more..

  • Page - 123

    106 Chapter 5 Summary In this chapter, I’ve, by necessity, rushed through the basics of new JavaScript DOM and API features; there really are too many for me to cover, so I’ve chosen what I think are the most useful. I’ve focused on those that improve the loading of scripts, those that facilitate easier DOM traversal and manipu- read more..

  • Page - 124

    6 DE V I CE A P I S In the previous chapters, I’ve discussed some of the many APIs that have been introduced as part of the HTML5 process, such as microdata and Touch Events. But there is a further range of APIs that, although not part of the spec, are certainly related; and these APIs offer something extremely attractive read more..

  • Page - 125

    108 Chapter 6 This is a curated list of those APIs I feel will be most practical, and the introductions to many are, for reasons of space, quite brief; often, the APIs will be much more extensive, and although I’ll note where I think the scope is available for you to learn more, I urge you to discover for yourself the read more..

  • Page - 126

    Device APIs 109 You can try this for yourself in position-current.html; my results are shown in Figure 6-2. Figure 6-2: Coordinates obtained through the geolocation object, referencing the street I live on; please don’t stalk me. Occasionally an error is returned when looking for the position; an optional error callback can check for this. The read more..

  • Page - 127

    110 Chapter 6 Orientation The Orientation API detects changes to the device’s position in 3-D space— that is, movement up and down, left and right, and clockwise and counter- clockwise. This movement is measured with an accelerometer, and the devices that are most likely to contain one are those that are most portable; mobile phones and tablets move read more..

  • Page - 128

    Device APIs 111 The three key properties that are germane to movement are alpha, beta, and gamma. Each is measured with a number representating degrees of rota- tion, although some are constrained within set limits. alpha measures rotation around, not movement along, the z-axis—that is, if the device were laid flat on a table, clockwise or read more..

  • Page - 129

    112 Chapter 6 In the next code snippet, a click event listener is applied to the element #trigger, which, when fired, will put .target into fullscreen mode, as long as permission is granted. You can see this for yourself in the file fullscreen.html, which is illustrated in Figure 6-4. var el = document.querySelector('.target'), launch read more..

  • Page - 130

    Device APIs 113 When an element has been put in fullscreen mode, you might want to style it (or its children) a little differently. It’s proposed that you can do this with a new dedicated CSS pseudo-class, which will be called either :fullscreen or :full-screen: .target:full-screen {} Vibration The Vibration API makes a device vibrate, read more..

  • Page - 131

    114 Chapter 6 You can try the API for yourself in the example file vibration.html, even though obviously you’ll need to open it on a mobile device with vibration capabilities if you want to actually feel the vibrations. If you don’t have one on hand, Figure 6-5 shows a recon- struction of the experience. Battery Status One of the key read more..

  • Page - 132

    Device APIs 115 The Battery Status API also has a series of events that fire when a change to any of the attributes is detected: chargingchange, chargingtimechange, dischargingtimechange, and levelchange. The following code uses chargingchange to detect a change to the device’s charging status and fires an alert if the status has changed: var read more..

  • Page - 133

    116 Chapter 6 Network Information also has an event handler, change, on the connection object, which fires whenever the connection status changes; with this, you can easily add an extra call to the function when necessary: connection.addEventListener('change', showStatus, false); You can see both at work in the file network.html—try connecting read more..

  • Page - 134

    Device APIs 117 In line , I’ve supplied two arguments to the getUserMedia() method: The first is the stream options where I’m flagging that I want to get video, no audio; and the second is the callback function where I’ve given the result a unique ID of stream. In the next line , I’ve used querySelector() to assign read more..

  • Page - 135

    118 Chapter 6 Figure 6-7: A key:value pair stored in the browser, shown in the WebKit Web Inspector NOTE Although I’m storing only very simple values in these examples, in most browsers, you can store up to 5MB of data for each subdomain. This is the figure recommended in the specification, although it’s not mandatory. You can read more..

  • Page - 136

    Device APIs 119 window.addEventListener('storage', function (e) { var msg = 'Key ' + e.key + ' changed from ' + e.oldValue + ' to ' + e.newValue; console.log(msg); }, false); Storage is being taken even further with the development of the Indexed Database (IndexedDB) API, which aims to create a full-fledged storage data- base in the browser that read more..

  • Page - 137

    120 Chapter 6 All of the events in the Drag and Drop API create an object called dataTransfer, which has a series of relevant properties and methods. You want to access these when the drop event is fired. For img elements, you want to get the URL of the item, so for this you use the getData() method with a value read more..

  • Page - 138

    Device APIs 121 Using the contains() method means you can perform different actions on different files. The example file drag-drop-2.html shows two elements, an img and a p, which can be dragged into the marked drop zone, creating a copy of each, and the following code shows how this is done: The contains() method detects if the element read more..

  • Page - 139

    122 Chapter 6 target.addEventListener('drop', function (e) { var files = e.dataTransfer.files, fileNo = files.length; e.preventDefault(); for (i = 0; i < fileNo; i++) { var el = document.createElement('li'), smth = document.createTextNode(files[i].name); el.appendChild(smth); e.currentTarget.appendChild(el); } }, false); If read more..

  • Page - 140

    Device APIs 123 You can also use a number of APIs to go even further with files: The File Writer API allows you to modify the content of a file, and the File System API goes further still with the provision of a navigable filesystem on the user’s device. These APIs are exciting but somewhat too technical for me to go into read more..

  • Page - 141

    124 Chapter 6 Summary By necessity, I could detail only a few of the many APIs that make up the web platform, including those for location and spatial movement, status of the battery and Internet connection, access to the camera and microphone, local storage capabilities, interaction with files and elements in a tactile way, and access read more..

  • Page - 142

    7 I M A G E S AN D G R AP H I C S For many years the only way to display images on the Web was to use JPGs and GIFs, with the former generally used for photographs and the latter for icons and graphics. These formats were later joined by the PNG format, which largely ousted the GIF (for icons at least, although not for animations read more..

  • Page - 143

    126 Chapter 7 In this chapter, I’ll walk you through the basics of each format, show- ing some common examples and giving you enough information so you can choose when each format is appropriate. Before I start, however, I’ll briefly explain some key terms and concepts. Comparing Vectors and Bitmaps Vector graphics are made of read more..

  • Page - 144

    Images and Graphics 127 The main reason SVG is so useful is its scalability, which I discussed in the previous section. Scalability is a real boon for responsive web design. You can reuse the same image across every platform, avoiding the problems with adaptive images, which I discussed in Chapter 3. In addition, the way that SVGs read more..

  • Page - 145

    128 Chapter 7 information. For example, here’s how to draw a circle whose center is 50px from the left of the grid (cx) and 75px from the top (cy), has a radius of 25px (r), a black border (stroke) 2px wide (stroke-width), and a background color of silver (fill): <circle cx="50" cy="50" r="25" stroke="black" read more..

  • Page - 146

    Images and Graphics 129 SVG Sprites SVG’s scaling capabilities are an especially good fit for using sprites for icons—that is, showing only a selected portion of a single large image to cut down on the number of file downloads and to speed up page load— although a little setup work is required. The way it works is that all of read more..

  • Page - 147

    130 Chapter 7 With this setup completed, you can link directly to the icon you want, using its id value in the URL, as shown here: .bar { background-image: url('foo.svg#icon1'); } The :target pseudo-class is applied when the hash of a URL matches the id of an element; in this case the URL hash is #icon1, so the :target read more..

  • Page - 148

    Images and Graphics 131 Similarly, you can use the object element, with the path to the SVG file used as a value for the data attribute: <object data="foo.svg"></object> With either of these approaches to embedding SVG, you can access the markup through the DOM by using the getSVGDocument() method, which returns an object read more..

  • Page - 149

    132 Chapter 7 as the fill attributes in this example, are presentational and, therefore, affected by CSS. And as SVG is part of the DOM, no special methods are required to interact with the element through script, meaning you can use standard DOM scripting like this: var svg = document.querySelector('svg'); console.log(svg.childNodes.length); This easy read more..

  • Page - 150

    Images and Graphics 133 <feGaussianBlur stdDeviation="3" in="SourceGraphic"/> </filter> </defs> <image xlink:href="foo.jpg" filter="url(#filter1)"/> </svg> Figure 7-5: A photograph before (left) and after (right) an SVG filter is applied You can combine multiple filter effects into a single read more..

  • Page - 151

    134 Chapter 7 You can apply filters to entire blocks of HTML using SVG’s foreignObject element, which acts as a container for snippets of markup as long as the markup is correctly formatted XHTML. The next example shows how this works. There are a few things to note: First, foreignObject has a requiredFeatures read more..

  • Page - 152

    Images and Graphics 135 Like CSS3, SVG2 will be modular, allowing for staggered development and implementation, meaning you could start seeing elements of it sooner rather than later. A Drawback of SVG For all the advantages of including SVG in your documents, one of its key strengths—accessibility via the DOM—is also its key weakness: Being read more..

  • Page - 153

    136 Chapter 7 Then you begin drawing. As with SVG, drawings are carried out with a series of shapes and lines, using a coordinate system. For example, to draw a rectangle filled with a solid color you use the fillRect() method, which accepts four number arguments: The first two are x- and y-coordinates of the top-left corner; the read more..

  • Page - 154

    Images and Graphics 137 Image Manipulation Canvas becomes extremely useful when manipulating images. You can load an image into a canvas and, once there, draw and manipulate it as you wish. Get the image data with the getImageData() method, which uses four argu- ments—the now familiar x, y, width, and height—to select the portion of read more..

  • Page - 155

    138 Chapter 7 Figure 7-9: The image on the right has been manipulated using canvas to invert the colors. Rather excitingly, you can combine the canvas element with the live video stream obtained from the getUserMedia() method I described in Chap- ter 6, providing image manipulation on the fly. Although I don’t have the space to read more..

  • Page - 156

    Images and Graphics 139 Where SVG excels is in its scalability, which makes it suitable for any screen regardless of size or resolution. As it creates new elements in the DOM, SVG is very useful for interacting with and being manipulated by JavaScript. And it’s also much easier to make accessible by adding alterna- tive and read more..

  • Page - 157

    140 Chapter 7 You can find a good range of canvas tutorials, from beginner to expert level, at, and an excellent cheat sheet with all of the core properties and methods on Jacob Seidelin’s blog at (last updated in 2009 but still relevant). HTML5 Rocks has read more..

  • Page - 158

    8 NE W FOR M S The motivating factor behind the creation of Web Applications 1.0, the original pro- posal that evolved to become HTML5, was to extend the power of HTML forms to allow the creation of rich and flexible online applications. HTML5 doesn’t disappoint, bringing a whole new range of elements, attributes, and read more..

  • Page - 159

    142 Chapter 8 you to pick a date. Given HTML5’s stated aim of standardizing common design patterns, it comes as no surprise that these common form elements should become part of the specification. Other than new widgets and form interactions, the most common use of JavaScript in forms is to check for errors while the read more..

  • Page - 160

    New Forms 143 and a URL. The fields look identical to a text input but have a key differ- ence: They limit the data that users can enter into them. Here’s how these values are used: <input type="email"> <input type="url"> The email type accepts only a well-formatted email address—peter@, for example—and the url read more..

  • Page - 161

    144 Chapter 8 The value of sympathetic layouts becomes really obvious when you use an on-screen keyboard that doesn’t support them; switching among differ- ent views for letters, cases, numbers, and symbols becomes a real chore. So help your users out by implementing these new types wherever and when- ever you can. New Attributes Before moving on read more..

  • Page - 162

    New Forms 145 Most browsers style the placeholder text lighter than the default color to show that it’s holding text rather than a value, but depending on your website’s color scheme that may not be ideal. Unfortunately, no standard- ized selector is available to change placeholder text properties, although some browsers have implemented read more..

  • Page - 163

    146 Chapter 8 form One of the limitations of forms in HTML 4.01 was that all form elements, including the submit button, had to be contained within the form element itself, meaning that, unless JavaScript were used, all the elements had to follow each other subsequently in the markup, limiting the ways they could be laid read more..

  • Page - 164

    New Forms 147 Figure 8-3: Auto-suggested results from a datalist element This association between the id and list attributes means that multiple inputs can refer to the same datalist element, if required. In browsers that don’t support datalist, the input box falls back to a standard text input. Please keep this in mind if read more..

  • Page - 165

    148 Chapter 8 Figure 8-4: The number and range types as displayed in Chrome for Android Both of these types have some new attributes in common: max and min are number values that set the maximum and minimum (did you work that out for yourself?) permitted values, and step is the number by which the value is incremented or read more..

  • Page - 166

    New Forms 149 The implementation method varies across browsers, with mobile and tablet devices varying quite significantly from desktop and laptop browsers. You can see some examples of this variety in Figure 8-5. Figure 8-5: The native date-picker widget on the Chrome for Android tablet (left), the iPhone (center), and the Chrome desktop read more..

  • Page - 167

    150 Chapter 8 Figure 8-7: A datetime picker on Chrome for Android So putting that all together, you could use attributes somewhat like the following, where the month input would allow the user to select only dates between January 2012 and June 2016; the step attribute would be in play only if the stepDown() and stepUp() methods were read more..

  • Page - 168

    New Forms 151 Figure 8-8: Chrome uses the native color picker of your OS for the color element; here’s how it looks in Ubuntu. Displaying Information to the User As well as accepting input from users, sometimes displaying information back to users is helpful, perhaps to show their progress through filling out a long form or the results read more..

  • Page - 169

    152 Chapter 8 Updating the bar using script is easy, requiring only a change of the value attribute, perhaps in a function somewhat like this one, where any value supplied as an argument to the updateProgress function updates the progress bar accordingly: var progressBar = document.querySelector('progress'), updateProgress = function (newValue) { read more..

  • Page - 170

    New Forms 153 Introducing the optimum attribute changes the behavior slightly, as it can introduce a third level of “acceptability” de pending on where it’s posi- tioned. For example, given the meter element in the previous example, you could say there are three ranges: low for any value of 0.2 or less, high for any 0.8 or greater, read more..

  • Page - 171

    154 Chapter 8 defaultValue, which gets or sets a default value (if none is supplied). To show how this works, I’ve written a short script that updates the output element when a range input is changed. Here’s the markup: <label for="output">Output</label> <input type="range" id="range"> <output id="output" read more..

  • Page - 172

    New Forms 155 This attribute forces the browser to check the value of the field; an empty or improperly formatted value is invalid and returns an error, and only a properly formatted value allows you to submit the form. The field’s type determines the pattern of the value format—email requires an email address, url requires a URL read more..

  • Page - 173

    156 Chapter 8 And you can do this at a more local level with the formnovalidate attri- bute on an input or button element. <button type="submit" formnovalidate>Go</button> This option is useful when you want to have an option to submit with- out validation. For example, in a content management system, allowing the user read more..

  • Page - 174

    New Forms 157 var valid = e.currentTarget.checkValidity(), validMsg = e.currentTarget.nextSibling, status = (valid) ? ' ' : ' '; validMsg.textContent = status; } email.addEventListener('input', checkStatus, false); You can try this in the example file checkvalidity.html, which also runs the script on a tel input that accepts only numbers. As well as read more..

  • Page - 175

    158 Chapter 8 Figure 8-14: The validityState object logged in Firebug, showing the current state of validity for the form field Browsers that have native validation alerts create their own messages that appear on screen; for example, submitting an empty input that has the required attribute applied displays the message “Please fill in read more..

  • Page - 176

    New Forms 159 Forms and CSS A new range of CSS pseudo-classes, known as the UI element states pseudo- classes, augments the extra functionality provided to forms by HTML5. These pseudo-classes let you style form elements based on their current interaction or validation state. The names of the pseudo-classes are really quite descriptive, read more..

  • Page - 177

    160 Chapter 8 Summary From humble beginnings, forms in HTML5 are now tremendously flex- ible and powerful, providing natively much of the functionality that we as developers have been adding in with JavaScript over the years. The new input types alone are a welcome addition, especially for those of us who use dynamic soft keyboards, read more..

  • Page - 178

    9 MUL T I ME D I A Although audio and video have been a popular part of the Web for many years on sites such as YouTube, Dailymotion, and SoundCloud, they’ve always been second-class citizens, relying on third-party plug-ins (especially Flash) to operate. A reliance on plug-ins isn’t a good long-term plan for website owners or read more..

  • Page - 179

    162 Chapter 9 For these reasons, having audio and video natively in the browser is extremely important, and one of the big pushes in HTML5 has been toward making this happen in the form of a pair of media elements that are widely implemented in browsers today. These elements control playback of audio and video from read more..

  • Page - 180

    Multimedia 163 using the autoplay attribute and make it loop indefinitely (until the user pauses it or leaves the page) by using the loop attribute; both are Boolean, so they require no value: <audio src="foo.oga" autoplay loop></audio> WA R N I N G Autoplayed sound has accessibility drawbacks; see the WCAG Audio Control read more..

  • Page - 181

    164 Chapter 9 Note that these attributes set the size of the video element, not the video itself, so if the values you supply aren’t in the same ratio as the file, the video won’t be stretched to fill the space; it maintains its aspect ratio and position in the center of the element, as you can see in read more..

  • Page - 182

    Multimedia 165 <video> <source src="foo.ogv" type="video/ogg"></source> <source src="foo.webm" type="video/webm"></source> <source src="foo.mp4" type="video/mp4"></source> </video> The example file media-elements-sources.html demonstrates this feature; the file appears to be the same as media-elements.html, read more..

  • Page - 183

    166 Chapter 9 FORM AT WA RS As I’ve mentioned a couple of times already, no single audio or video format is supported by all browsers, meaning you have to use a few different source files to accommodate everyone. The reason for this is patents and licensing. I don’t want to go into too much detail as it’s a bit of a read more..

  • Page - 184

    Multimedia 167 This code is quite lengthy, but it does seem to cover all eventualities. Kroc Camen developed it, and I recommend you read his article “Video for Everybody!” to see all of the notes and caveats that I was unable to include here (see “Further Reading” on page 175). Subtitles and Captions You can add optional text tracks read more..

  • Page - 185

    168 Chapter 9 Different browsers accept different types of files for subtitles and cap- tions, but the emerging standard is known as WebVTT. This format is simple, displaying captions from a start time to an end time. Here’s an example: WEBVTT 1 00:00:00.500 --> 00:00:04.000 Hello to all readers 2 00:00:06.000 --> 00:00:10.000 Thanks for reading read more..

  • Page - 186

    Multimedia 169 file, which sets certain parameters on it. To set a time range, as in this notional example, you would use something like this: <audio src="foo.oga#t=4,8"></audio> The #t notation is a shortcut for a time range, with the two comma- separated values after it representing the start time and end time in read more..

  • Page - 187

    170 Chapter 9 var playPause = document.getElementById('play-pause'), video = document.getElementById('video'); playPause.addEventListener('click', function () { if (video.paused) {; } else { video.pause(); } }, false); Figure 9-4: A simple Play/Pause toggle created using the Media Elements API The attributes of media elements are read more..

  • Page - 188

    Multimedia 171 If the user has interacted with the seek bar and the media is in the pro- cess of moving to a new position to resume playback, the seeking property returns true. You can get the duration of the media with the duration prop- erty and the time that playback begins with initialTime; both also return a value in read more..

  • Page - 189

    172 Chapter 9 property with the current value divided by 100 (to match the scale of the volume). You can try this for yourself in the file media-volume.html and see it in Figure 9-6: var video = document.querySelector('video'), volume = document.getElementById('range'); volume.addEventListener('change', function (e) { video.volume = e.currentTarget.value / 100; read more..

  • Page - 190

    Multimedia 173 Perhaps more useful though is the readyState property. This property is similar to the previous one in that it has value states, but these report on the readiness of the media to be played—whether it has loaded the meta- data, loaded the file fully, and so on. The five states are: 0 when no information about the read more..

  • Page - 191

    174 Chapter 9 For example, the following code logs a message into the console when a video file has reached state 4—that is, sufficient data is available for the media to play through until the end: video.addEventListener('canplaythrough', function () { console.log('Can play through.'); }, false); For the playback state, playing is fired when the media read more..

  • Page - 192

    Multimedia 175 proposal aimed at allowing all web-connected devices to communicate with each other, using audio, video, and data in real-time and using a single stan- dardized protocol. At the moment, many tools do this, but all of them require plug-ins or extra software, and very few actually use the same protocol and are able to talk to read more..

  • Page - 193

    176 Chapter 9 The best introduction to WebVTT and the track element is on Dev.Opera,, and a use- ful WebVTT validation tool is on Anne van Kesteren’s website, http://quuz .org/webvtt/. I mentioned three encoding tools in this chapter: The FFmpeg command-line tool is at read more..

  • Page - 194

    10 WE B AP P S So far, most of this book has been about web technologies that can be used anywhere, from open websites to device- specific web apps. In this chapter, I’ll take a short detour to talk about the extra steps required to create applications—how you can adapt your site to make it available through an online read more..

  • Page - 195

    178 Chapter 10 In this chapter, I’ll look specifically at the latter two types, web apps and hybrid apps, and at how to make them available through some of the many application stores. But even that’s not as simple as it sounds: Many rival platforms and stores exist, each has a different development platform and submission read more..

  • Page - 196

    Web Apps 179 Hosted Web Apps A hosted app is one that holds all files on an external web server, usually accessible via a public URL. Essentially, a hosted app is like a website with a little extra metadata to allow app stores to index it. A hosted app isn’t installed onto a device; a shortcut is created on the device that read more..

  • Page - 197

    180 Chapter 10 app’s root folder. The following annotated code shows a short example of manifest.json for the Chrome Web Store, with the bare minimum of required fields. { "name": "App Name", "description": "Short description", "version": "0.1", "manifest_version": 2, "icons": { read more..

  • Page - 198

    Web Apps 181 "version": "0.1", "launch_path": "", "icons": { "128": "icon_128.png" } } The name and version fields and the icons object are the same as previously described for the Chrome Web Store. The description field is the same too, except read more..

  • Page - 199

    182 Chapter 10 PhoneGap Although owned by Adobe, a commercial entity, PhoneGap is free, open source software that allows you to build semi-native mobile applications using web platform technologies. PhoneGap is a distribution of software called Apache Cordova, which used to be called PhoneGap before it was sold to Adobe and things became complicated. read more..

  • Page - 200

    Web Apps 183 Other properties require heightened permissions and, as such, are available on some platforms exclusively through PhoneGap. For example, consider the contacts object, which provides access to the user’s contact list— not something you want exposed to the Web without special authorization. The contacts object has two functions: create() and read more..

  • Page - 201

    184 Chapter 10 Other events include pause and resume. The former is fired when the cur- rent application is closed and moved to a background process, and the lat- ter when it becomes active again. For example, you may want to store data when the application is moved to a background process to make sure users doesn’t lose their read more..

  • Page - 202

    Web Apps 185 Webinos If your goal is to develop for true cross-device communication, you may want to consider the Webinos framework. This open source, browser-based application platform is co-funded by the European Union together with major players such as BMW, Samsung, Sony, and the W3C. It’s intended to simplify communication between read more..

  • Page - 203

    186 Chapter 10 Contents of the AppCache File The .appcache file begins with the words CACHE MANIFEST and then follows with a list of all files that should be cached. Each file is on a new line, and you can add single-line comments by entering a hash (#) at the start of each line. The following listing shows a manifest file that read more..

  • Page - 204

    Web Apps 187 If the manifest file exists and has been loaded before, the browser loads all the files held in the cache first, followed by any other files that are required to load the page. Next, it checks to see if the manifest file has been updated and, if so, downloads another copy of all the listed files. These files are read more..

  • Page - 205

    188 Chapter 10 var myCache = window.applicationCache; myCache.addEventListener('updateready', function(e) { if (myCache.status === myCache.UPDATEREADY) { myCache.swapCache(); if (confirm('Load new version?')) { window.location.reload(); } } }, false); By requesting permission to reload the page, this script ensures that the user doesn’t read more..

  • Page - 206

    Web Apps 189 You can read more about the Titanium project at platform/. Each smart TV platform has its own developer forum, but a good example for getting started is Samsung’s site at The Opera TV Store is gaining some traction as a custom-made solu- tion; learn more about it at read more..

  • Page - 207

    read more..

  • Page - 208

    11 T H E FUTU R E So far in this book I’ve aimed to discuss only those web features that are pretty stable in at least a few browsers, or that should be stable sometime in the near future. But now that we’ve arrived at this last chapter, I can really cut loose and talk about some of the more experimental read more..

  • Page - 209

    192 Chapter 11 Web Components I don’t think I’m exaggerating when I say that the Web Components speci- fication proposes the most radical changes to HTML since its creation some 20+ years ago. Even the much-hyped HTML5 is a small point-version update that doesn’t really add anything genuinely new. Web Components is a read more..

  • Page - 210

    The Future 193 the browser. This means images and other external elements aren’t loaded and included scripts won’t run, which can be a real performance boost com- pared to hiding elements with CSS, where assets are still loaded. A template is declared with the template element, and any child ele- ments form the content of the template. read more..

  • Page - 211

    194 Chapter 11 You can see it for yourself in the example file templates.html; the output is shown in Figure 11-1 (see Appendix A for information on current browser support). Note that in order for the contents of the template element to show in the DOM, I had to enable the Show Shadow DOM option in my devel- oper tools; if read more..

  • Page - 212

    The Future 195 Let’s break this down into stages. The following code shows an example of a decorator. I gave it the unique id #foo (for a change). Inside is a tem- plate that contains a div, with the content element and an h2 inside that. <decorator id="foo"> <template> <div> read more..

  • Page - 213

    196 Chapter 11 You can see this in action in the following code: A scoped style tag is used inside a div element, and the rules applied to the h1 apply only to the h1 within that element (the one with the id of #foo), and not the one outside the div (with the id #bar). The scope of the rule applies only to the read more..

  • Page - 214

    The Future 197 Custom Elements Although decorators are handy for adding extra presentational markup to an element, when you want to make more substantial changes, use a custom element. The key difference between custom elements and decorators is that the latter are transitory; they can be applied or removed by changing an attribute or read more..

  • Page - 215

    198 Chapter 11 be reused across many documents. As a result, many of the cumbersome wid- gets we build today (such as carousels, accordions, and date pickers) could be applied to existing elements without filling the DOM with unnecessary markup, with the added benefit of implementing encapsulation to avoid conflicts. I mentioned earlier that the read more..

  • Page - 216

    The Future 199 When this code executes, users see an h2 element with the text 'Hello, shadow world! ', but if they viewed the DOM, users would see the original content, 'Hello, world! '. The h1 element has been completely replaced by the new shadow node tree. The DOM remains unaffected. Figure 11-3 shows how this renders in read more..

  • Page - 217

    200 Chapter 11 Putting It All Together I’ve only brushed the surface of the Web Components specification, but I hope I’ve offered enough to get you excited by the possibilities. Web Components promises to offer fully reusable code components to enhance existing elements. These components will be fully encapsulated from the rest of the read more..

  • Page - 218

    The Future 201 Regions work like this: An element is declared as a source, and the content of that source is flowed into another element, or series of elements, known as a region chain. What that means in practice is you can have content flowing across multiple elements in a sequence that doesn’t flow in natural DOM read more..

  • Page - 219

    202 Chapter 11 Figure 11-4: Using CSS Regions, you can flow content across multiple elements that don’t need to be adjacent. Exclusions CSS Exclusions can be thought of as a kind of positioned floats—indeed, an earlier concept described them as exactly that. In CSS2.1 you can float elements only to the left, where other content flows read more..

  • Page - 220

    The Future 203 Figure 11-5: An element that’s absolutely positioned doesn’t affect the flow of the content beneath it. (This gorilla photo is by Chris Willis and can be found at http://www.fotopedia .com/items/flickr-3059127796/. It used under a Creative Commons license.) The following example uses the keyword value both to make content flow read more..

  • Page - 221

    204 Chapter 11 Figure 11-7 shows a few of the different values at work. The first example has a value of start, so the content flows to the left of the exclusion element. The next has the end value, so the content flows on the opposite side. And in the final example, the clear value makes content flow on neither side of the read more..

  • Page - 222

    The Future 205 Under the usual rules of grid placement, element G would stack over the top of element F, as it appears later in the DOM order. But by making element G the exclusion element, the inline content of element F will flow around it: G { grid-row: 2; wrap-flow: both; } As you can see in the example file read more..

  • Page - 223

    206 Chapter 11 they solve different problems. With the CSS specification in a constant state of flux, however, nothing can be taken for granted; these rules and proper- ties may be implemented, partially implemented with a different syntax, or not implemented at all. Still, I think looking at them is worthwhile for two reasons: First, so read more..

  • Page - 224

    The Future 207 Feature Queries In Chapter 5 I discussed the JavaScript library Modernizr, which is used for detecting the existence of certain features in a visitor’s browser, and briefly mentioned its native adaptation into CSS through the @supports at-rule. I want to return to that now and explore it in a little more detail, as it’s read more..

  • Page - 225

    208 Chapter 11 The Modernizr project has already begun implementing this in its library; if native CSS.supports() implementation is present, the script will use that, and if not, it will fall back to Modernizr’s own tests. Cascading Variables Variables have proven their utility over the years in just about every program- ming language, but read more..

  • Page - 226

    The Future 209 For example, in the following code the custom property var-foo, with a value of #F00, is declared on the :root element, but I’ll also add a differ- ent value and selector below it. In this case, the value of the variable would be #F00 for the whole document, but it will now be #00F for the .bar ele- ment read more..

  • Page - 227

    210 Chapter 11 The Shadow DOM is the best-implemented piece of Web Compo- nents and, as such, has more online documentation. Both Sitepoint and HTML5 Rocks have clearly written explanations of the topic, which you’ll find at and http://www If your browser read more..

  • Page - 228

    A B R O W SE R SU PP OR T A S OF MAR C H 2 0 1 3 Documenting feature implementation in browsers means aiming at a moving target, so the best I can do is take a snapshot. When considering whether to use one of the features in this book, always check the following sites for the most up- to-date information: HTML5 Please, read more..

  • Page - 229

    212 Appendix A has been slower than I anticipated for some of the features contained in Internet Explorer 10 (such as Grid Layout, Regions, and Exclusions), but everything else is proceeding apace. The Browsers in Question Far too many browsers exist for me to provide a decent overview of feature support on each. Instead, in this read more..

  • Page - 230

    Browser Support as of March 2013 213 In Chrome, the process is much the same except that you enter chrome://flags, no warning message appears, and the features are usually enabled by toggling a link marked Enable . Chapter 1: The Web Platform Every major modern desktop browser comes with a set of developer tools that includes a console (only read more..

  • Page - 231

    214 Appendix A The viewport-relative length units—vh, vw, etc.—are in IE9 (with a few bugs) and IE10, Firefox, and most WebKit browsers except Android, but not present in Opera. The rem unit is in IE9 and above and all other major browsers. The object-fit and object-position properties are implemented in Opera only and marked as read more..

  • Page - 232

    Browser Support as of March 2013 215 Chapter 6: Device APIs The Geolocation API is in IE9 and all other major browsers. Device orien- tation is present in mobile WebKit browsers, Chrome, and Firefox mobile. Do bear in mind, however, that device APIs depend on certain functions being available on the phone; just because the Device read more..

  • Page - 233

    216 Appendix A Rather than try to capture that here, I’ll refer you to the HTML5 Test, which has the most comprehensive and up-to-date coverage. Using the new input types is generally considered safe, as the browser will fall back to the text type if a different value is not recognized. The Constraint Validation API is read more..

  • Page - 234

    B F U R T H E R R E A D ING This appendix is simply a collection of all of the links contained in the “Further Reading” section of each chapter, brought together in one place for your convenience. My plan is to host this list on the companion website,, and update it with new and interesting links as read more..

  • Page - 235

    218 Appendix B You can find a good primer on the IoT in The Next Web’s article “Why 2013 Will Be the Year of the Internet of Things”: http://thenextweb .com/insider/2012/12/09/the-future-of-the-internet-of-things/. David Storey wrote a great post about the non-smartphone mobile web, “See your site like the rest of the world does. On the read more..

  • Page - 236

    Further Reading 219 The LabUp! website is a resource for finding or getting involved with open device testing labs: The chief tester at the BBC, David Blooman, wrote a long and detailed article, “Testing for Dummies,” about how a global organization performs multi-device testing: http:// read more..

  • Page - 237

    220 Appendix B If you want to learn more about the RDFa format, the W3C published an excellent primer: The best resource for learning about microdata comes from the HTML5 Doctor again: If you’re feeling masochistic and prefer to read the spec in detail, you’ll find it read more..

  • Page - 238

    Further Reading 221 The history of the current favorite responsive images proposal, and latest news on the state of its adoption, can be found on the website of the Responsive Images Community Group: respimg/. Find Matt Wilcox’s Adaptive Images tool at Chapter 4: New Approaches to CSS Layouts The read more..

  • Page - 239

    222 Appendix B Modernizr’s website,, has full documentation plus a configurable build system and also plays host to “The All-In-One Entirely-Not-Alphabetical No-Bullshit Guide to HTML5 Fallbacks” (their title, not mine) at HTML5-Cross-browser-Polyfills/. Christopher Coenraets wrote an excellent read more..

  • Page - 240

    Further Reading 223 Chapter 7: Images and Graphics You can find a great introduction to SVG at the SVG Basics website: http://, and the W3C’s own SVG Primer is a useful way to dig deeper: MDN has a quite complete list of elements and attributes: read more..

  • Page - 241

    224 Appendix B Bruce Lawson’s discussion of autofocus accessibility, “The Accessibility of HTML 5 Autofocus,” is on his blog at the-accessibility-of-html-5-autofocus/. HTML5 Rocks has a good overview of the Constraint Validation API at A useful application read more..

  • Page - 242

    Further Reading 225 Chapter 10: Web Apps The Chrome Web Store has in-depth documentation on preparing an app for submission, including details about the manifest file, at https://developers Firefox Marketplace provides details about the manifest file at https://, and it has a useful read more..

  • Page - 243

    226 Appendix B The Shadow DOM is the best-implemented piece of Web Compo- nents and, as such, has more online documentation. Both Sitepoint and HTML5 Rocks have clearly written explanations of the topic, which you’ll find at and http://www If your browser read more..

  • Page - 244

    Symbols and Numerals @import at-rule, 40 @supports at-rule, 102, 207 @viewport at-rule, for setting viewport parameter, 49–50 . (dot) notation, for storing items, 117 [] (square bracket) notation, for storing items, 117 3-D axes, 110 3-D context detecting device position in, 110 WebGL for, 138 3-D orientation, information sources, 124, 222 A a element, read more..

  • Page - 245

    228 Index audio format, variation in browser support, 166 audio() method, 173 AudioContext() method, 174 auto value for column-fill property, 67 for height property, 60 for preload attribute, 163 autocomplete attribute for form, 145 autofocus attribute for form, 144 autoplay attribute, for media elements, 163 avoid-column value, for break-before property, 69 read more..

  • Page - 246

    Index 229 child elements, in grid, 78 Christian, Mark, 189, 225 Chrome (browser), 3 enabling experimental features in, 213 Chrome for Android, Geolocation opt-in prompt, 108 Chrome Web Store, 178 documentation from, 188, 225 manifest file for, 179–180 Chromium, 212 circle element in SVG, 127–128, 131 circles, arc() method for, 136 Cisco, 10, 217 classes read more..

  • Page - 247

    230 Index CSS layouts, Flexbox (continued) changing content order, 71–72 checking browser for properties, 101 declaring model, 70–71 information sources, 87, 221 wrap and flow, 76–78 Grid Layout module, 18, 78–86 alignment and stacking, 83–84 Exclusions and, 204–205 grid declaration and definition, 79–80 grid template, 85–86 information sources, 87, 221 key terms, 78, read more..

  • Page - 248

    Index 231 device emulators, 19 device libraries, 212 device pixel ratio (DPR), 46, 48 media feature to target, 47 Device Storage API, 123 device-aspect-ratio feature, 43 device-height media feature, 43 deviceorientation event, on window object, 110–111 devicePixelRatio DOM property, for window object, 46 deviceready event, in PhoneGap project, 183 devices, read more..

  • Page - 249

    232 Index explicit sectioning, 23 extends attribute, of element element, 197 external stylesheets, use based on media, 40 F fallback files, 186 fallbacks, for media elements, 165–167 feature phones, 3 feature queries, 207–208 information sources, 210, 226 feGaussianBlur element, 132 feMorphology filter, 133 FFmpeg, 168 information sources, 176, 224 figure read more..

  • Page - 250

    Index 233 G game console browsers, 6 information sources, 10, 218 gamma property, for orientation, 111 gaps between columns, 67–68 Gaussian Blur effect, for SVG graphic, 132 Geolocation API, 108–109 information sources, 124, 222 geolocation object, 108 getContext() method, 135 getCurrentPosition() method, 108 getData() method, 120 getElementByClassName() method, 97 read more..

  • Page - 251

    234 Index HTML forms, new attributes (continued) placeholder, 144–145 spellcheck, 145 on-screen controls and widgets, 147–150 color, 150 dates, 148–150 numbers, 147–148 HTML parsing, JavaScript blocking of, 90 HTML5, 13 best practices, 15–16 embedding SVG in, 130–132 new elements, 22–26 purpose, 23–24 responsive images solution, 62–63 schedule for read more..

  • Page - 252

    Index 235 J JavaScript, 89–106 browser support, 214 for canvas element, 135 Firefox’s experimental implementations of, 16 Firefox OS and, 123 for HTML5 and IE, 25 information sources, 106, 221–222 libraries, 89, 98–104, 200 jQuery, 98–100 Modernizr, 101–102 Mustache, 102–104 YepNope, 100–101 new features, 90–98 addEventListener method, 91–94 async read more..

  • Page - 253

    236 Index M main axis, in Flexbox, 73 main role, 27 Manian, Divya, 28, 38, 219 manifest attribute, of html element, 185 manifest files information sources, 188, 225 for web apps, 179–181 manifest.webapp file, 180 master entries, 186 matchMedia() method, 52 max attribute for date or time, 149 for meter element, 152 for number input type, 148 read more..

  • Page - 254

    Index 237 Mozilla Developer Network. See MDN (Mozilla Developer Network) Mozilla, Firefox OS and WebAPIs, 123 MP4 format, 166 Multi-column Layout module, 66–70 gaps and rules, 67–68 information sources, 87, 221 items spanning multiple rows or columns, 82 spans and breaks, 68–70 multimedia, 161–176 advanced interaction, 174–175 browser support, 216 media elements, read more..

  • Page - 255

    238 Index organization, in hCard pattern, 30 orientation three-dimensional, information sources, 124, 222 of viewport, 44 Orientation API, 110–111 :out-of-range pseudo-class, 159 output element, 153–154 overflow-style property, 206 P Paciello Group Blog, 38, 219 packaged web apps, vs. hosted, 178–179 PadFone (Asus), 7 page elements, percentages for, 53–54 page structure. read more..

  • Page - 256

    Index 239 Rel-Tag microformat, 29 rem (root em), 56–57 remoteItem() method, 118 remove() method, 97 removeEventListener() method, 93–94 repeat() function, 81 replaced objects, and responsive websites, 58–63 requestFullScreen() method, 111–112 required attribute, of input type, 154 :required pseudo-class, 159 Resig, John, 38, 220 resizing objects, 60 resolution read more..

  • Page - 257

    240 Index Sitepoint, 210, 226 sites. See websites smart TVs information sources, 189, 225 Internet-connected, 184 smartphones, 3–4 PPI count, 45 use stereotypes, 8 snapshots, in JS Bin, 105 soft keyboard, for form input, 143 software development kits (SDK), 19 Souder, Steve, 40 source element, 62, 64, 220 SourceGraphic keyword, 132 space-around read more..

  • Page - 258

    Index 241 terminology, 12 testing, 19 browsers for JavaScript support, 51 in JavaScript, 105 text files, content as, 122 text input, 142 text tracks, for media files, 167–168 Theora format, 164 three-dimensional. See 3-D... timeupdate event, 171, 174 Titanium, 184 information sources, 189, 225 toggle() method, 98 top value, for object-position property, 61 read more..

  • Page - 259

    242 Index videoWidth attribute, 173 viewport dimensions of, 41 length units relative to, 56–59 media query to apply stylesheet, 58 orientation of, 44 viewport meta tag, 49 @viewport at-rule, for setting viewport parameter, 49–50 Vision Mobile, 10, 217 volume property, for media elements, 171 volumechange event, 174 Vorbis format, 164 vw unit, 56 W W3C (World read more..

  • Page - 260

    Index 243 X x-axis, 110 rotation around, 111 XML file manifest file as, 179 SVG file format as, 127 Widget manifest file as, 181 X-Tags, 210, 226 Y y-axis, 110 rotation around, 111 YepNope, 100–101 information sources, 106, 221 properties used in Modernizr, 102 Z z-axis, 110 rotation around, 111 z-index property, 84 Zakas, Nicholas, 124, 222 Zepto, 100 read more..

  • Page - 261

    read more..

  • Page - 262

    read more..

  • Page - 263

    read more..

  • Page - 264

    The Modern Web is set in New Baskerville, TheSansMono Condensed, Futura, and Dogma. This book was printed and bound at Edwards Brothers Malloy in Ann Arbor, Michigan. The paper is 60# Williamsburg Smooth, which is certified by the Sustainable Forestry Initiative (SFI). The book uses a RepKover bind- ing, in which the pages are read more..

  • Page - 265

    PHONE : 800.420.7240 OR 415.863.9900 EMAIL : SALES @NOSTARCH.COM WEB : WWW .NOSTARCH.COM THE BOOK OF CSS3 A Developer’s Guide to the Future of Web Design by PETER GASSTON MAY 2011, 304 PP ., $34.95 ISBN 978-1-59327-286-9 LAND OF LISP Learn to Program in Lisp, One Game at a Time! by CONRAD BARSKI , M .D. OCTOBER 2010, 504 PP ., $49.95 ISBN read more..

  • Page - 266

    $34.95 ($36.95 CDN) w w T H E F I N E ST I N GEEK EN T E RTA I N M E N T™ “I L I E F L AT .” This book uses RepKover — a durable binding that won’t snap shut. SH EL VE IN : COMPUTERS/WEB PROGRAMMING Today’s web technologies are evolving at near–light speed, bringing the promise of a seamless read more..

Write Your Review