- Economics & Finance
- Health & Medicine
- Step by Step
HTML5 Hacks introduces readers to the umbrella of HTML5 specifications through 90 hacks.
www.it-ebooks.info read more..
www.it-ebooks.info read more..
Jesse Cravens and Jeff Burtoft HTML5 Hacks www.it-ebooks.info read more..
ISBN: 978-1-449-33499-4 [LSI] HTML5 Hacks by Jesse Cravens and Jeff Burtoft Copyright © 2 013 Jesse Cravens, Jeff Burtoft. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are read more..
Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii 1. Hacking the Semantic Way . . . . . . . . . . . . . . . read more..
Hack 24. Turn Transforms into Animations with CSS3 Transitions 110 Hack 25. Make iOS-Style Card Flips with CSS Transforms and Transitions 113 Hack 26. Use Respond.js to Polyfill CSS3 Media Queries in IE 117 Hack 27. Control Mobile Layout with the viewport read more..
Hack 56. Cache Media Resources Locally with the FileSystem API 255 Hack 57. Build a Milestone Calendar with IndexedDB and FullCalendar.js 264 7. Geolocation Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..
Hack 81. Use Node.js’s Response Object to Respond to the Client with Device-Specific Data 450 Hack 82. Use the Node Package Manager to Add a Web read more..
expect the browser to provide natively. Flattening the API landscape, if you will.” In our opinion, the best polyfill is one that lets you write your code just as you would if the feature were natively supported, and that does the work in the background when nec- essary, being transparent to both the user and the developer. In most circumstances, each HTML5 read more..
HTML5 Implementations As an eager developer ready to move forward with implementing some of the new features available in this text, it will be important to understand that many of the HTML5 specifications are in experimental stages of development. One major chal- lenge in writing a book about evolving specifications is keeping the information fresh and up to date. read more..
1 http://en.wikipedia.org/wiki/Hacker HTML5 Lint This means that developers should also be ready to use a lint tool in order to expose stylistic issues within their code. Some of the more common issues to check for are consistent indentation, lowercase tags, and omission of closing tags. At the time of this writing, we recommend the HTML5 Lint tool. References for read more..
1. Hacker (computer security), someone who accesses a computer sys- tem by circumventing its security system 2. Hacker (hobbyist), who makes innovative customizations or combina- tions of retail electronic and computer equipment 3. Hacker (programmer subculture), who shares an anti-authoritarian ap- proach to software development now associated with the free software movement It is read more..
Chapter 6, Client-Side Data Storage Hacks Discusses storage and HTML5 application cache Chapter 7, Geolocation Hacks Teaches how to work with geolocations Chapter 8, WebWorker API Covers taking advantage of the WebWorker API Chapter 9, Hacking HTML5 Connectivity Discusses web sockets, cross-document messaging, server-side events, and more Chapter 10, Pro HTML5 Application Hacks with read more..
writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s read more..
Safari® B ooks Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s lead- ing authors in technology and business. Technology professionals, software developers, web designers, and business and cre- ative professionals use Safari Books Online as their primary resource for research, problem solving, read more..
Guest Hackers John Dyer is the executive director of Communications and Educational Technology at Dallas Theological Seminary. He has been a web developer and technology writer for more than 10 years, and he loves creating tools that make complex tasks easier for other developers. He lives in the Dallas area with his two amazing kids and his lovely wife, Amber. read more..
www.it-ebooks.info read more..
HACK 01 1 Hacking the Semantic Way The spirit of HTML5 is simplicity. HTML5 has made it easy to implement web stand- ards that in the past have been difficult to implement. Instead of trying to reinvent the Web, visionary consortiums such as the WHATWG (Web Hypertext Application Tech- nology Working Group) and the W3C (World Wide Web Consortium) looked at the read more..
HACK 02 HTML5 says farewell to all that, and keeps it simple: The browser uses the to know how to render the web page. Most browsers didn’t download the DTD from the URL, but they did change their behavior based on the . If a browser encountered the preceding code, it would switch to standards mode (as opposed to quirks mode) and apply XHTML read more..
Web designers and developers have long conformed to structural components on a page. A common high-level page structure may look something like the following: Take note of the “structural” s in the page. This reflects well-organized content and a clean structure for the page. The problem with the preceding code is that almost every element in the markup is a . read more..
You can see pretty quickly where this gets messy, yet we don’t want to abandon the idea of structural elements that declare page segments—many code readers, such as screen readers and search bots, have come to rely on structural conventions. As with many parts of HTML5, the new structural tags have provided a simple solution to the problem of added read more..
HACK 03 We’ll get into the attributes later in this chapter, but for now you just need to understand that this solution allows you to keep the structural elements of the page and let third-party components apply identifiers to the nodes, while freeing up the attributes for the page author to control. Take note, third-party developers: never as- sume that read more..
You’re feeling pretty good about yourself until you remember that some of your visitors are not using HTML5 browsers, and being the web standards elitist that you are, your page has to be backward-compatible. Don’t throw those HTML5 tags out the window just yet. This hack will teach you how to write your code once, and use it on all the browsers out read more..
The Fallback div In the preceding code sample, the element is not recognized and is passed over at render time. Since the DOM does not recognize these elements, option 1 uses a fallback element that the browser does recognize, and wraps each unrecognized element in it. The following code should make this easier to understand: Voilà! We can now style the element read more..
switched from to and realized he lost the ability to style unrecognized elements. Fast-forward to 2008, when John Resic realized he could ex- ploit the same bug to make HTML5 elements recognizable in IE; he named the capa- bility the “HTML5 shiv,” although it is technically a shim. Here are the details. Old versions of IE don’t recognize HTML5 elements read more..
HACK 04 Bring Back the <input> Tag HTML5 has breathed new life into the tag. It’s time to get excited once again about this “age-old” tag. I have to admit that I was getting a little bored with the tag. Before HTML5, any real interaction had to be done outside the tag: whether the interaction involved validation, formatting, or graphical presentation, read more..
If you try hitting the Submit button without putting a value in the field, your browser will throw up a default message along the lines of “Please fill out this field.” It’s not perfect, but it’s a start. The attribute is a feature that has been a long time coming. Have you ever wanted to have a form on your page, but without constraining the form read more..
1 http://www.w3.org/TR/html5/common-input-element-attributes.html#the-autocomplete- attribute The autocomplete Attribute The Web definitely has a fascination with autocomplete. Since we all hate to type, we love it when the element knows what we want to type and just does it for us. So HTML5 comes along and introduces autocomplete as a simple attribute. You set to or read more..
The list Attribute Think of the attribute as being a version of for developers. The attribute is tied to an of a (yes, once again this is not a name or any other type of identifier, it has to be an ). It will look something like this: The level of interaction is what you would expect from an autocomplete feature: press the “D” ke y on read more..
Figure 1-3. Datalist displaying predefined options One of the bad things about both and is that you can’t style them. I’ll rant about that some more as we get into a few of the more functional input types, such as , but I would expect to be able to style the results with CSS, just as I do any form element. The pattern Attribute How many times have read more..
HACK 05 If you don’t meet the pattern criteria the form cannot be submitted, and instead you get a user agent message that says something like “Please match the requested for- mat.” One of the big problems with this implementation is its lack of adherence to modern web patterns. Back in the day (2005 or so) we used to wait until a form was submitted to read more..
Notice that the validity state rolled up to the form. If any one of the inputs within the form doesn’t meet the criteria for validation, the form rule will return as well. This is a key feature when you have long forms. For instance, if I have a form with 25 input fields that need to be validated, I don’t want to have to go through the read more..
Measurable attributes Some types have comparative criteria such as , which require a strict input pattern. Other types have attributes such as and that must be satisfied before the input can be considered valid. Let’s look at our first input example again: In this case the number that is input must meet the and criteria in order to be considered read more..
Note that the form is still invalid. If you call the method on this form, it will still return . In the case of the attribute, you simply ignore whether the form is valid or not when you submit. The second way to escape validation is with the attribute. In a similar manner, the attribute is added to the element itself, and every but- ton and read more..
Our form will now give us an option for a friendlier, more helpful user error. Notice that we had another method in the tag and set it to the of the . When you use you automatically trigger the other portion of your Constraint Validation API to return when you call the method. In order to use a custom method and still have the form be read more..
Figure 1-4 shows our rendered view. Figure 1-4. Form with validation for required field The CSS in the preceding code snippet adds a red border around the invalid field. The red border will remain until the proper content is entered. 22 HTML5 HACKS www.it-ebooks.info read more..
We had to do this in two different ways due to browser support. The easy way was the method we used for the email address. The knows what a valid input address looks like (i.e., the pattern of the address, not whether it works). So once a valid string is set to the proper value, the field will no longer appear with a red border. The method we read more..
Figure 1-5. The YUI date picker, which provides a clean interface for date selection This is a huge improvement over having the user enter the date into an input field and hoping that it meets the required format. With the YUI date picker, we can stylize the component with CSS and make it look like it blends right in with our app. This has served our purposes read more..
In terms of context, here’s the great thing about the preceding example. As it stands, the date selector will be pretty tough to use on my iPhone; not only is it hard to see, but also my fingers are pretty fat and those tap zones are pretty small. So in iOS 5 and later, Apple has kindly implemented the date input field shown in Figure 1-7. Figure read more..
Increment at which a date can be selected. The spec doesn’t clarify all the incre- ment types that a user agent must adhere to, but day, week, month, and year are obvious implementations. A date value that represents the minimum date the input will consider valid. It’s not clear whether the controller will allow you to choose dates below the date, or whether it read more..
It’s also interesting to note that there are a few variations on the input type of , and each provides noteworthy interface challenges, especially on mobile and touch devices. Here are some similar types to keep your eye on: • • • • • The range Input Type Once again, let’s look at one of our great polyfill libraries to get an idea of what the read more..
When you’re selecting ranges, nothing is worse than typing in values, especially when you’re “exploring” what will happen when thos e ranges change. The slider has become a standard tool on both web and desktop devices. You generally have a bar represent- ing something like numeric values or colors, and a handle that you drag from one end of the bar to the read more..
to be since the most popular shoe size in our little store is size 3. (Yes, we do cater to elves, leprechauns, and small children.) The allows you to choose the “default” value that make s the most sense, not just what’s in the middle. The HTML5 version of the sliders also has the added benefit of being able to match the other browser read more..
The color Input Type You may not have thought of a color picker as being essential to a user’s web experi- ence, but as the Web becomes more of an application environment, complex activities such as picking colors need to be responsive and adaptive. The input type allows you to select a color value from within the input. Support for this input type is read more..
Figure 1-10. The <meter> tag as it appears in Chrome for Windows This particular form element has some interesting UI controls. You can see from the preceding example that the meter needs to have a value set, as well as a range, to be effective. The and attributes will set the range (the meter is completely empty and the meter is completely full, read more..
Figure 1-11. The <progress> tag as it appears in Internet Explorer 10 The code implementation would be as follows: The tag has only a few configuration attributes, and both are shown in the preceding code. The first is the attribute that tells you what your progress “goal” is . The value will be the top of your meter; the bottom will always be zero. Your read more..
Form Elements and Making Them Look Good One thing all form elements have in common is that they look bad. Since I first started working with forms nearly 15 years ago, I’ve been trying to find ways to make them look better. A perfect example of this is the drop-down menu. Drop-downs look pretty simple. However, it’s difficult to do anything special with read more..
then lack the ability to adapt to the context in which they are being used. Remember the drop-down menu I complained about earlier? Well, iOS has found a way to turn it into a brilliant user input on the iPad and iPhone. On the iPhone it becomes a spinner input at the bottom of the screen (see Figure 1-12). On the iPad it becomes a drop- down window in read more..
HACK 07 Know What’s Going On in Your App with New DOM Events HTML5 provides a slew of new events for you to latch on to. The world has moved beyond mouse clicks and keyboards. Now the Web has, too. DOM events haven’t changed much in the past 15 years. I think the last new DOM event we got was the mouse scroll (that’s what you call that little read more..
Similarly, we have two additional events that can be attached to the input field: and . The event fires once the attribute is upda- ted. You may not immediately see the need for an event, since we do have and numerous other events that can be triggered on an input change. But let’s think about some of the new HTML5 elements, such as the read more..
Endless fun, right? We now have the best of both worlds: built-in validation with real- time responsiveness. Other New Events While we are on the subject of events, HTML5 is proposing the adoption of a slew of new events similar to the ones mentioned in the preceding section. Most of these events focus on a user action, and they fire before, after, and read more..
HACK 08 Add Rich Context to Your Markup with Custom Data HTML5 formalizes the ability to store data directly in the page element. The data is simple to add, and just as simple to access. Custom data attributes give us the ability to add more richness and depth to our markup than we’ve ever been able to before. Custom data attributes, often called the read more..
2 http://dev.w3.org/html5/spec/single-page.html#attr-data A custom data attribute is an attribute in no namespace whose name starts with the string “data-”, has at least one character after the hyphen, is XML- compatible, and contains no characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).2 In summary, it’s an attribute that starts with read more..
Then we had to use CSS to hide the first row (with a class name of ): Another really bad solution involved using one of the existing attributes to store this data. In the following example the data is stored in the attribute: There are so many problems with this solution that it’s hard to know where to start. First, it’s a horrible idea to read more..
HACK 09 Before, HTML5 browsers simply recognized the value as an attribute of the element, so a simple method of the element would retrieve the data. Note that in this method, the “data-” part of the value is required to retrieve the data. There is one more way to access this data, but it comes with a warning. Most current browsers support a CSS3 read more..
We’re not going to talk too much about event delegation; there are plenty of books and other resources out there that explain the details behind all of that. But it is im- portant to know what event delegation is and why we do it. Event delegation is the act of passing (or bubbling, to use a more accurate term) the captured event from an inner element read more..
Figure 1-13 shows the results. Figure 1-13. Our simple content Custom data attributes allow us to “inline” data in our elements by setting a string to the attribute of the element. (For a more in-depth look at custom data, see Hack #08 .) We are using an HTML5 page “primer” (the ba se page that we edit to get a quick start on development) called read more..
If you’re like me, you believe that in the future, machines will rule over us humans with an iron fist (provided, of course, that the Zombie Apocalypse doesn’t get us first). While there isn’t anything we can do to help the zombie masses understand the In- ternet, HTML5 does offer a feature that prepares us for that machine dictatorship. It’s called read more..
As you can see, we have constructed one data item on our page, and when the markup is machine-read it will see the item as something like this: Now let’s build ourselves a whole list: 49 CHAPTER 1: HACKING THE SEMANTIC WAY www.it-ebooks.info read more..
To our human friends, the page looks something like Figure 1-14. Figure 1-14. Adding microdata to the page, which does not change the view for users To our machine friends, the code looks something like this: 50 HTML5 HACKS www.it-ebooks.info read more..
www.it-ebooks.info read more..
2 Hacking with Style I remember designing websites without CSS. It was horrible—lots of tables and images and image maps. Back in the day, most sites took several minutes to load because generally they were so overladen with image hacks in an effort to achieve a decent design. Then CSS came along and it was spectacular! Suddenly the Web had stand- ards, read more..
HACK 11 features. It’s also good during development, or while implementing one of the examples within this book, to attempt to use the features with the proper CSS3 attribute directly, and then only add the browser prefix if the func- tionality fails. CSS3 is a powerful tool, but due to the high level of features it offers in the experimental release phase, it read more..
It’s common to see CSS3 implemented with a style declaration, and then repeated each time with the browser prefix of each browser that has early support for that feature. Your CSS may look something like this: This gives flexibility to the developer to utilize CSS3 features on the browsers that support them and not affect the browsers that don’t. Let’s read more..
HACK 12 1 The generic font families that each browser supports are the following: serif, sans-serif, mono- space, cursive, and fantasy. It’s ultimately up to the development community to keep browser prefixes in check. When you write CSS with browser prefixes, consider all browsers that support that feature. Utilize the browser prefixes when necessary, but do your part read more..
Without any additional changes, every browser will apply the Radley font to the body text of the page if it has this font installed. As it’s extremely unlikely that a user will have this specific font, the CSS3 declaration can be applied to greatly improve the chances of this particular font being available for use. The declaration needs to be made read more..
We’ve added three distinctive fonts on this page (in addition to some traditional fonts we used in the primer page). The first thing we want to do is to bring the fonts into the page so that we can access them. This is where the import comes in: Each font has two declarations in the . The first is the local name of the font. It’s a good read more..
Notice that our fallback fonts are still listed in our declaration. If the browser fails to load the font, we want the browser to fall back to its best alternative. With a few imports and a few new CSS declarations, we’ve given our page that custom design that gives it much needed character, and sets it apart from the rest! Working with Different read more..
This works just fine; you can access the normal, bold, and italic versions of your fonts. But it’s a real mess to implement, and it’s prone to human error. Let’s go back to those imports and define these same characteristics when we import them: 60 HTML5 HACKS www.it-ebooks.info read more..
HACK 13 By setting the style and weight on the import, we can control the style and weight with simple, familiar attributes. This helps us keep our CSS clean, and since we now build our declarations just like we would with any font, we are a lot less prone to error. A Few Things to Note: Support and Performance IE 5 started supporting web fonts more read more..
2 http://www.google.com/webfonts#AboutPlace:about There is another problem that can put a damper on “fun with fonts”: the legal system. Just because you have access to a font doesn’t mean you have the right to use that font in your web application. It definitely doesn’t mean you have the permission to distribute the font—and yes, putting a font on a publicly read more..
The fonts available through the Google Web Fonts service are also open source. This helps you immensely with the legal aspect of font use. Each font you find in the service will already be curated to make sure it is licensed for you to use. This not only helps you avoid any questions about your permission to use the fonts, but it also means you don’t read more..
Figure 2-3. Google Web Fonts collection showing page performance impact of utilizing three fonts 65 CHAPTER 2: HACKING WITH STYLE www.it-ebooks.info read more..
Nontraditional Font Access Although Google offers a number of options for loading web fonts, there may be some scenarios that just don’t fit into the provided options. Don’t lose hope. There is a hack for this situation, too! Google Web Fonts allows you to take your fonts with you. Nestled in the corner of each Use page is a link to download all the read more..
Common Mistakes Utilizing fonts can require a lot of work, and doing it well can require even more work. A lot of effort went into making Google Web Fonts easy to use, but there are a few easy- to-make mistakes to bring to your attention. In some cases it can be too easy to load web fonts on your page—so easy that you can be prone to load read more..
their HTML tags. A common example is an indentation of each list item ( ) nested inside an unordered list ( ). Another common style is to make headers larger and heavier than all other text. Typical text has a font weight of 400; most browsers set a default font weight for headers at 700. Let’s look back at that Use page for the Bitter font. This read more..
Figure 2-6. Inconsolata font on an h1 header allowing its default font weight of 700 to be utilized Since a version of Inconsolata in a font weight of 700 isn’t available, the browser kicks in and tries to compensate by applying its own version of bold to the font. This usually ends in a noticeably ugly product. Luckily, the solution is fairly simple. You read more..
HACK 14 Either option will guarantee a pristine implementation of your web font. For more information about Google Web Fonts, visit the product home page. Use CSS3 Text Effects to Make Your Text Not Suck CSS3 text effects finally give you control over your text. Explore some of the newest and greatest text control features with CSS3 text effects. CSS has always been read more..
And here is the markup: Now, CSS3 is truly awesome! The attribute allows your text to break within a word to the next line. CSS will add a hyphen at the word break by adding an additional attribute of . Now your HTML can lay out text just like your word processor. The Text Shadow Property Sometimes what makes type so impactful isn’t just the read more..
HACK 15 Distance of horizontal shadow, negative or positive Distance of vertical shadow, negative or positive Size of blur of text, optional Color of shadow It’s as simple as that—a drop shadow test without the weight of Flash or images! Other Text Controls CSS3 adds a list of additional text controls that give you more control over your text and expand the read more..
children (such as ). Opacity does neither. Opacity passes on the char- acteristic. In the preceding example, every child element inside an element with a class of will also have opacity of 50%. This isn’t an inherited property that can be changed or reset. Let’s look at an example of nested opacity: In the preceding example, the text will render with opacity read more..
Figure 2-11. Overlapping circles with opacity set to 50% Figure 2-12. Overlapping circles with alpha transparency set to 50% Figure 2-10 has no opacity settings and no alpha channel, which renders it with full visibility. Figure 2-11 has 50% opacity set on each circle and Figure 2-12 has the trans- parency channel set to 50%. As you can see, the color circles read more..
The new alpha transparency allows us to set the transparency where we set the color. This could be to a background color, a gradient, a drop shadow, or any other property that takes a color value. It inherits with the color value only, and doesn’t affect the presentation of child elements. There may be times when opacity and all its inherited characteristics read more..
HACK 16 Use Media Queries to Build Responsive Design Your web page can look just as great on a mobile phone as it does on the desktop. The secret to achieving this feat is called responsive design, and media queries are the key to making your pages responsive. Mobile is all the rage these days. And with HTML5, the mobile web is even hotter. The industry read more..
Figure 2-14. Our example website as viewed through mobile Safari on an iPhone 4s The website is hard to utilize in its current state. The iPhone does give us the ability to “pinch and zoom” the page so that we can read it, but it’s not a great experience. Although it is accessible, it certainly doesn’t cater to my device. Let’s take a look at read more..
In order to make the website respond to our device, we want to lose the multicolumn layout and stack all our content into one column—in essence, we want to move from a horizontal layout to a linear one. Currently, our page splits our window space into three columns and places content into each column. Our new layout will convert those columns into read more..
In Come the Media Queries Congratulations! You have a responsive design! Now you need to program the browser to know when to use one design over the other. In come the media queries. Media queries allow you to place conditions around your CSS to tell it whether it should apply the CSS declarations inside the condition or not. There are a number of read more..
HACK 17 tag The media query can be set in the tag. Then the declarations within that file are only applied to the page if the media query is satisfied: condition A block of CSS can be wrapped within curly brackets in the CSS document, and the CSS declarations are only applied to the document if the media query is satisfied: condition An import will read more..
its side), mobile devices can be viewed in either landscape or portrait mode. Most mobile phones and tablets have an accelerometer inside that recognizes the change in orientation and adjusts the screen accordingly. This allows you to view content on these devices in either aspect ratio. For example, the iPad has a screen aspect ratio of 3:4 where the device is read more..
Figure 2-17. Our sample page in portrait mode on an iPad, with one column of linear content Here is the CSS for the three-column view: and the CSS for the single-column view: 83 CHAPTER 2: HACKING WITH STYLE www.it-ebooks.info read more..
Now we’ll wrap each CSS option in media queries so that they only apply in their proper orientation. Remember, the media queries wrap the CSS in conditions that only apply the declarations when the media query resolves to . Using inline media queries (see Hack #16 for an explanation of other implementation options), our CSS will now look something like this: read more..
HACK 18 Media queries based on orientation can often be simpler. You don’t need to know what screen size to expect for landscape versus portrait view. You simply rely on the ori- entation published by the device. You also gain consistency between devices in terms of how the pages appear in each orientation. The argument against orientation media queries is pretty read more..
Each CSS declaration applies to elements not through class names, IDs, or tag names, but through other characteristics that meet the pseudoclass criteria. The CSS Zebra Stripe Data Table Let’s look at an example that focuses on DOM relations (how an element relates to its parent element). A nice feature to have on tables with a large amount of data is a read more..
HACK 19 Without any CSS, every row of this table will be the same color. Now let’s use an pseudoclass to color our rows. This pseudoclass takes a keyword (such as or ), a number, or an expression. For our example we will use the keyword, but we could have easily used an expression such as . Let’s look at our table CSS: Our table will now read more..
Figure 2-18. Sample table with our zebra stripe CSS using the nth-of-type pseudoclass to apply a light blue shade to every other row Figure 2-19. Image sprite pulled from Google Gmail application 88 HTML5 HACKS www.it-ebooks.info read more..
This sprite has just about every icon used within the Gmail application. Now let’s look at the code that turns this big image into each small icon. Here is the markup: And here is the CSS: This code renders an icon next to my name in Gmail. You can see that the background position defines what part of the image is shown. The height and width of the icon read more..
the sprite that you may not need in each image, but sprites do often reduce the total size of the image payload. Since images on a page often look similar, a shared color palette between the images reduces the file size. The more you group similar images together, the more you save. The Problem with Image Sprites Although sprites solve the problem of read more..
The preceding code would produce a 32 × 32 image that looks like Figure 2-21. Figure 2-21. HTML5 logo icon To implement this in your CSS, just replace your normal URL with the Base64 version of the image: To implement the data URI in an image tag, set the to the preceding string: 91 CHAPTER 2: HACKING WITH STYLE www.it-ebooks.info read more..
HACK 20 It’s that simple. But I’m sure you’re wondering how you can convert these images (that were previously sprited as one image) into data URIs. Luckily many tools are already available on the Web for this very task. My favorite is Data URL Maker. With this tool you can quickly upload an image and convert it into Base64-encoded characters. The Downsides of read more..
Gradients are images that contain smooth color transitions between two or more col- ors. They are widely used in graphic and web design to create classy-looking back- grounds, slick buttons, and interesting visual effects for your pages. Historically, you needed to use an image editor such as Photoshop or GIMP to create an image containing your gradient, save it in a read more..
Pure CSS Gradients The good news is that CSS3 introduced pure CSS gradients, among many other great features. These enable you to specify all your gradient settings—colors, orien- tation, and so on—as pure CSS, allowing for much better flexibility and improved performance. In a perfect world, the previous example would simply become: Another benefit of using CSS read more..
If you want to add support for older IE versions and additional browsers, things be- come even crazier with additional CSS declarations, each having its own syntax. Tools such as the ColorZilla Ultimate Gradient Generator were created in order to save you from this multibrowser syntax mess, and make pure-CSS gradients simple. With this tool, you can use a familiar UI read more..
Figure 2-26. Using the color handles to specify the beginning and end colors of the gradient Now copy your CSS directly out of the tool (see Figure 2-27). Figure 2-27. The CSS generated from the ColorZilla Ultimate Gradient Generator Designing and customizing gradients The ColorZilla Ultimate Gradient Generator has options for designing and customizing your gradients. For read more..
Figure 2-29. Gradient color stops You can also create gradients with varying opacities, which is great for seamlessly blending your gradient with other visual elements. For example, you can create a gra- dient that goes from being opaque to being transparent, and then you can position it above an image. The varying opacity of the gradient will gradually reveal or read more..
HACK 21 Figure 2-32. The final result, with the gradient overlaying the image Additionally, the tool includes a number of presets if you prefer not to start your gra- dient designs from scratch, and you can also save your favorite designs in the tool. Modernizing your old gradients The ColorZilla Ultimate Gradient Generator allows you to import your existing gradi- ents read more..
The Border Radius The border radius has been a sought-after feature for years, as it’s a design pattern that has been mimicked with background images or pixel size elements in countless applications. The border radius is fairly straightforward to implement: The border radius implies having a border, so first you must state a border property in your declaration. You need read more..
The Box Shadow Web designers have long used drop shadows to give elements a sense of depth on a web page. CSS has finally formalized this capability with the native box-shadow fea- ture. The box-shadow feature adds true drop shadows to your elements. Implemen- tation requires you to declare the horizontal and vertical offsets (both numeric values), the optional read more..
The Border Image One of the most powerful new features in CSS3 is the border image. In essence, this feature lets you utilize an image file as your border, as opposed to solid colors. Border images can be difficult to utilize at times, as the property patterns may not follow other border attribute conventions. The attribute is stated as follows: Let’s read more..
Figure 2-35. Button with borderImageClass applied Figure 2-36 shows the image we are using to create the button. Figure 2-36. Image used to render the button The inward offset of this image essentially divides the image into nine parts. Figure 2-37 shows the image again with our inward offset drawn in. Figure 2-37. Image used to render the button with an read more..
HACK 22 Figure 2-38. Final button with image border New border features have given us a lot of design flexibility. Gone are the days of using fixed images for each visual treatment. Border radius and box shadow meet a lot of our design needs, and most of the remainder can be addressed with border images. Set Multiple Background Images to the Same Element The read more..
Figure 2-39. Example of our panoramic view requiring multiple background images shown on a small screen The syntax for multiple background images is simple and intuitive. The properties are written just as they were in previous versions, with comma-separated lists for the different “layers” of backgrounds: Our image required three background images: the trees are in one read more..
Figure 2-40. Example of our panoramic view requiring multiple background images shown on a larger screen How It Works Here’s how it works. Each declaration creates a background “layer” on y our element. If you have four declarations, you will have four layers (note that we have three in our class). Each property can have a comma-delimited list as well. The read more..
HACK 23 Notice that a background color can only be defined on the final “layer” which renders as the bottom layer. This easy-to-implement feature shows the power and simplicity you will find all across the HTML5 family of technologies. Free Your Page Elements from Their Traditional Space with CSS3 Transforms CSS3 transforms give you the ability to add perspective to your read more..
Each element shown in Figure 2-41 has its corresponding class assigned to it. Notice the use of the x- and y-axes to transform each element. Our traditional square can take on many different perspectives with transforms. Figure 2-41. Repeated rectangle with corresponding class names added to demonstrate the transform effect CSS3 Transforms in 3D Three-dimensional transforms read more..
Specifies a 3D scale operation on the x-, y-, and z-axes Specifies a clockwise rotation by the given angle about the x-axis Specifies a clockwise rotation by the given angle about the y-axis Specifies a clockwise rotation by the given angle about the z-axis Value that determines the perceived distance of the 3D object (smaller numbers make objects appear closer) Once read more..
Figure 2-42. Repeated rectangle with corresponding class names added to demonstrate the transform effect You may not see a lot of value in 3D transforms right off the bat. When you move an element on the z-axis (or the 3D plane) it tends to just look like a different effect (such as 2D skew or a line), but hold on for the next hack where 3D meets read more..
And here is the CSS class that defines the original view of our markup: Notice that first we defined the width of our element to be set to 50%. This is the starting value we will be transitioning from. To start the transition, we need to add the new class (named ) to our element via some timer or user ac- tion. In this case, we will add a read more..
Figure 2-44. Illustration of the div after adding the button class name that starts the transition Transition to What? The attribute is not the only attribute that can take a transition. Here are some additional attributes that can be transitioned, according to the W3C spec: Make 3D Transitions with Transforms CSS3 transitions really shine when they are coupled with read more..
We’ve built out a few simple structural elements for our component. Let’s review them: In our example, this is the parent container for our component, but on a mobile device where this “card” will take up the whole screen, it’s important to under- stand your viewing area. On a mobile device, any transitions that would cause part of our elements to be outside read more..
The element is the that actually gets flipped with a transition, so our original property is assigned to this element in our CSS: Take special note of the transforms within this declaration. We set the transform style to 3D in order to have access to the x-, y-, and z-axes. Our transform origin sets the distance our element is from the read more..
There are really only two “functional” CS S attributes on these elements to call attention to here. The first applies to both elements, and is the attribute . The defines whether you can see the element inverted when you turn it around, or whether the element disappears. The default is , so in order to not have our s bleed through when the card read more..
HACK 26 This simple listener will add the class to the element if it doesn’t have the class, and will take it away if it does. Figure 2-46 shows how our pure CSS card flip looks now. Figure 2-46. iOS-style card flip re-created in CSS using CSS3 transforms and CSS3 transitions Now we have a good, old-fashioned iOS card flip. Use Respond.js to read more..
Figure 2-47. Our responsive website as viewed in the Google Chrome browser, version 15 Figure 2-48. Our responsive website as viewed in Microsoft Internet Explorer version 8 119 CHAPTER 2: HACKING WITH STYLE www.it-ebooks.info read more..
Figure 2-49. Our responsive website as viewed in Microsoft Internet Explorer version 8 after adding Respond.js to the page I told you it was easy! Caveats and Quid Pro Quo There are a few keys to achieving success with Respond.js. First, you will want to place the respond.js file directly after your last CSS tag. If you give your browser time to load read more..
HACK 27 Control Mobile Layout with the viewport <meta> Tag Browser makers have conformed to the use of a tag that helps your mobile and small-screen devices load a page as the author desired. This one tag can be the difference between a viewable website and one that is “made for mobile.” When smartphones with fancy HTML5 browsers hit the market, they read more..
Defines whether the user can scale the page (through pinch and zoom) This tag also allows you to specify characteristics of your site and control the presen- tation for your visitors. A picture is worth a thousand words, so let’s take a look at an example. Figure 2-50 shows a responsive web page with the tag, and Figure 2-51 shows the same page read more..
Figure 2-51. Sample web page designed for a mobile phone without the use of the viewport <meta> tag as viewed on an iPhone 4s Safari browser option for them to zoom in further if necessary. Generally, I leave the pinch and zoom feature on, unless I am using pinch and zoom for something else on the page (such as zooming into a map). You’ll find this read more..
From a high level, device adaptation is fairly simple. Let’s look at how we would declare the same tag we’ve been using for this hack: The property can be placed inside a style block on the page, or on any stylesheet. It can even be wrapped in a media query. I encourage you to review the specification before implementing it, as some of the property read more..
consume. This need has really come to a head with Apple directly excluding plug-ins such as Flash and Silverlight in order to better control battery and power consumption on iOS devices. This in turn has thrust HTML5 video into the mainstream. On today’s Web, if you want to support all your users HTML5 video is essential. Writing the Code HTML5 video isn’t just read more..
and With these attributes you can set the size of the video directly in the tag itself. These attributes will determine what size the embedded video is on the page, not the size of the file you are loading. The height and width do not necessarily need to match the original source. These attribute values are represented in pixels, which equates to stating read more..
HACK 29 Video As a First-Class Element HTML5 tags finally give you native control over your video. Unlike embedded objects such as Flash objects, HTML5 tags can be treated just like any other element on your page. One of the greatest advantages of this is the ability to control the element with CSS. Just as with any other element on the page, your read more..
The preceding code is nice and neat, but it only allows you to set one source for your tag. Let’s rewrite that tag to set the source as its own tag: This nested tag is the tag. This tag is used specifically to set multiple sour- ces for media tags. Your browser will play the first video file in the list of tags that it supports. If no read more..
HACK 30 Aren’t you glad that the standard supports more than one source file at once? As there is no one codec that is supported by all major browsers, it’s necessary to provide at least two different files to cover all major browsers. To be compatible with Apple and Internet Explorer browsers, you must support H.264, and then either OGG or WebM can be read more..
It’s important that we build a reference to this element so that we can use the reference instead of going back to the DOM (Document Object Model) every time. Now that we have the element identified, we will use it to call out custom controllers. The code should look something like this: If we were going to use the same controls we have read more..
Now when the Play and Pause buttons are hit the source will be added back into the element if it’s empty. The next two buttons in our control bar will be treated similarly. These buttons are the Skip Forward and Skip Back buttons. For our example we will skip five seconds forward in the video or five seconds back. Again, we will control these buttons by read more..
HACK 31 Figure 3-2. Video element with custom controls built on top of our HTML5 video element APIs A Word About Audio We’ve focused completely on tags for this hack, but we don’t want to neglect the fact that HTML5 audio fits into the same specifications as the tag ( ), so the same APIs exist for audio as they do for video. We can swap out our read more..
We basically have three page elements to work with, and each has a key role in our “production.” Source Video The source video is the video we start with. It’s basically a video of a rascally little boy on a green background. The source video will be played and the pixels from each frame will be pulled out and displayed on our first tag for read more..
Display Canvas The display canvas is the canvas we actually see. As we play our video and copy the frames to the first tag, we will pull that pixel-level data from the first canvas and analyze it to find the green screen portion of our video. The identified green pixels will then be removed and replaced with transparent pixels, allowing the background read more..
With our environment set up, we need to build a function that will make sure the video is playing. We do this by determining that the state of the video is not paused or ended. We will then invoke a new method called , which will run our video conversions. Finally, we will make this a self-calling method so that it will loop through itself until the read more..
HACK 32 The Results So, we have our video feeding into our tag, then running analysis on the data in that canvas which we process and display on our display canvas. We started with our rascally little boy video and our background image, and we ended with the wonderful Hollywood-style production shown in Figure 3-5. Figure 3-5. Our display canvas with our read more..
As an auxiliary benefit, you may also be helping the “speaker-impaired.” Speaker- impaired users are people like me, who lost the power supply from their desktop computer speakers and refuse to buy a new one because they’re going to find it one of these days. If my computer sound doesn’t work, subtitles can help me, too! Easy Implementation Subtitles are one read more..
This specifies the language of the track. The value must be a valid language code and is a required attribute if the track is of type . The VTT File The subtitles are actually stored in the WebVTT file that is referenced in the tag. WebVTT stands for Web Video Text Tracks and is a fairly simple file to format. Let’s look at our sample file: The file contains read more..
Figure 3-6. Video file with subtitle captions from the VTT file Karaoke Anyone? Subtitles can also be presented with inline timing tags. These will present your sub- titles in a “karaoke” or p ainted-on style. To accomplish this, we put timing tags within each cue text as follows: This cue will present the first half of the cue at second one, and will paint on read more..
HACK 33 Figure 3-7. WebVTT file with timestamps displaying text one segment at a time Summary It’s recommended that you include elements within all your tags that contain audio information. To increase the scope of your audience, it’s also good to include multilingual subtitles if possible. The Web has no boundaries, and now your HTML5 video files don’t either. read more..
Figure 3-8. HTML5 video file with basic WebVTT cues presented on the screen Basic Formatting from WebVTT Some basic formatting applies directly to video cues as part of the WebVTT specifi- cation. Here are the key attributes: / Changes the orientation of the text to be vertical or vertical with text from left to right. Determines the position from the top of the read more..
Each format should be placed beside the time range as follows: This provides your basic formatting. For more advanced styling let’s turn to CSS. CSS Styling For more advanced formatting, we can place format-friendly tags directly within the cues of our WebVTT file. Let’s look at a sample: HTML formatting is added directly into the text of the cue. Without any CSS read more..
With our CSS, the formatted cue will now look like Figure 3-10. Figure 3-10. WebVTT HTML-formatted cue with our CSS included which shows the word “reader” in boldface Pseudoclasses Within a Track Cue To easily identify the cue, you can use a CSS pseudoclass. Three pseudoclasses are available: The identifies the entire cue; the and are used to identify those read more..
HACK 34 A set of attributes can be used within this pure text environment. The set is limited to the following: • • • • • • • • • All other attributes will be ignored when applied to text inside a cue. Use the Cuepoint.js Polyfill for Subtitles At the time of this writing, IE 10 is the only HTML5 browser that supports subtitles. This hack read more..
Once you add these components to your page, the results will look like Figure 3-11. Figure 3-11. Video using the Cuepoint.js polyfill to support HTML5 video subtitles 149 CHAPTER 3: MULTIMEDIA HACKING www.it-ebooks.info read more..
HACK 35 Remember, it’s always important to use subtitles when your video has an audio track, and Cuepoint.js allows you to provide that essential functionality to all your users, regardless of the functionality of their browser. Easily Build Audio-Rich Applications with Buzz The term sound effects is traditionally ostracized in the web app world and passed off as cheesy read more..
Using the Buzz APIs Buzz has a lot to offer—in fact, too much to cover in this hack—so we will only look at some of the highlights of the library. I encourage you to visit the online documentation for a detailed list of all available APIs. The documentation is divided into four sections. Let’s look at some of the highlights of each. Buzz This is read more..
HACK 36 Audio has gotten a bad rap over the years, but what’s old is new again. Users have new expectations as to what they get from HTML5 apps. Don’t be afraid to pull Buzz into your app, and play sounds when the app calls for it. Be creative again! Simplify Your HTML5 Media with MediaElement.js HTML5 media is generally easy to implement, but with read more..
This allows you to use H.264-encoded MP4 files across all browsers and mobile de- vices. You can also use older FLV files you might still need to support (using the Flash shim) or even Windows Media files (using the built-in Silverlight plug-in). Responsive Video If you are working with a responsive layout and need your video content to resize accordingly, read more..
Captions and Subtitles The HTML5 spec also includes a tag that is used to load external text files that contain captions, subtitles, or chapter breaks. The proposed format is WebVTT, or Web Video Text Tracks, a simple text-based format that begins with a single-line declaration ( ) and then lists start and end times separated by char- acters, followed by the text read more..
4 Hacking Your Graphics with Canvas and SVG Over the past decade Adobe Flash became very popular because it allowed us to create and manipulate imagery directly within our web pages. This demand resulted in development of the Canvas specification. The tag is one of the most flexible of the new HTML5 tags. This has made the tag the new foundation for web-based read more..
HACK 37 Draw Shapes on Your HTML5 <canvas> Tag Flash became insanely popular because of the flexibility it brought to the browser. With Flash the Web was free from decorating DOM elements and became a platform for real drawing and animation. HTML5 brings this same type of flexibility and power directly to the DOM with the HTML5 tag. This hack starts us off read more..
Figure 4-1. The 200 × 2 00 <canvas> tag with grid markers every tenth point on both the x- and y-axes Drawing Rectangles We’ll start with one of the simplest shapes: the rectangle. These are easy to draw into the context of our tag. The context gives us access to the API to draw three basic types of rectangles: Draws a rectangle with a read more..
Figure 4-2. The 200 × 2 00 canvas demonstrating the different rectangle APIs in the <canvas> tag Each of the three APIs follows the same pattern. They are passed four parameters: the x and y coordinates, along with the width and height of the rectangle. Drawing Paths Rectangles are just the tip of the iceberg when it comes to drawing on a canvas. Most read more..
At this point our canvas will still be blank, as we have not yet closed our path. To close the path we use the following method: Now we have one line on our canvas. To create our grid, we want to draw multiple lines within our path. To accomplish this, we will begin the path, and then create a series of and methods. Once we have read more..
As illustrated in the preceding code, a number of arguments are passed into the method. The first two are the coordinates for the arc’s center, followed by the arc . The and parameters declare the start and end points of the arc in radians, which are measured from the x-axis. The final optional parameter, when set to , draws the arc in a read more..
This isn’t very exciting. So next we will add the mouth. For this we will use the method, and then draw a half circle (notice that the will be instead of as it was for the full circle): The last two components are the eyes. Since we want our eyes to be solid fills, we need to make separate strokes for each of them so that we read more..
HACK 38 Figure 4-4. The 200 × 2 00 <canvas> tag with the smiley face Advanced Drawing We’ve plowed right through lines and arcs, but many illustrations call for lines that can’t be accomplished by either of these shapes. The Canvas specification includes two additional tools for creating custom shapes: Each of these methods has control points and an ending x,y read more..
Shapes and strokes have little effect on our applications if we can’t apply color and styles to them. The specification for canvas styles borrows heavily from CSS, so a lot of the syntax should be familiar to you. Color Canvas elements can be colored with any CSS color value style, and they even support transparency with RGBA and HSPA colors. Also, canvas read more..
As soon as we started the second stroke with the method, we set a new, darker stroke style for the horizontal lines. There are two different methods for adding color to your shapes. ap- plies to lines and the outline of shapes, and applies to shapes or strokes that have a fill applied to them. It’s important to note that once you set a read more..
The preceding code provides us with the basic smiley face shown in Figure 4-5. Figure 4-5. The <canvas> tag with the smiley face illustration As every child who wasn’t raised by wolves knows, smiley faces are supposed to be yellow. Let’s redraw our smiley face with a yellow background: 167 CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG read more..
This gives us a more iconic version of our smiley face, as shown in Figure 4-6. Figure 4-6. The same canvas smiley face with a yellow fill on the head circle In order to accommodate the introduction of color, we had to make a few changes to our code. First, we extracted the mouth from the same stroke that made the head so 168 HTML5 HACKS read more..
that the fill would not overwrite the line used for the mouth. Then we added a fill method to the end of the head circle to color it yellow. The last change we made was to reset the fill color back to black for the eyes. Again, once we set the style, we needed to reset it to black to return to the default value. Now, to prove read more..
We have simply replaced our fill color with the gradient as a fill. This gives us the added depth we want to make our smiley face stick out from the crowd (see Figure 4-7). Figure 4-7. The smiley face canvas drawing with a gradient in place of a solid fill color Additional Styles You can accomplish a transparency effect with a color of your choosing, read more..
HACK 39 Because they play such a large role in illustrations, lines are given additional control values in your tag. You can set the following values for a stroke on your tag: A numerical value that represents the width in points The shape of the end of a line, which can be declared as butt, round, or square The shape of a line joint, which can be read more..
Figure 4-8. The 200 × 2 00 <canvas> tag with a drawing of a smiley face We set the background color by adding a color fill to the circle that makes up the head. Once the stroke is started, it’s a simple line of code: Our end result will have a simple image used as a repeating background (see Figure 4-9). Figure 4-9. The 200 × 2 00 <canvas> read more..
To change that solid color to an image, we will use a very similar API: You can see in the preceding code that we are using the same API for an image back- ground as we are for a fill color (similar to the background attribute in a CSS decla- ration). However, a bit of additional overhead is required when using an image. Using an Image as a Fill read more..
If we were to run this code, we would probably be disappointed with the results. In most cases, our smiley face would look like Figure 4-11. Figure 4-11. The smiley face canvas rendering with the background image set as in the previous code sample 174 HTML5 HACKS www.it-ebooks.info read more..
Can you identify the problem? Think about the load time. The canvas is taking ad- vantage of real-time data. In the preceding sample, we created the image and then set it as a background immediately. Since the pattern failed, the canvas fill reverted back to its default state of black for the fill color. The problem has to do with the availability of the image read more..
Now we’re sure that our image data has loaded, and the tag can take full advantage of the image for use in its pattern background. Easy Image Data Adding image s around whole segments of code can sometimes be cumber- some. A nice shortcut available in HTML5 browsers is the use of inline image data. We can easily remove the event from the preceding read more..
HACK 40 It may not make sense to utilize the Base64 version of your image in all cases, since it results in added weight in the initial page load, but sometimes it may be appropriate in order to utilize and simplify your code. It’s a good practice to have multiple imple- mentation methods to choose from. Use the HTML5 <canvas> Tag to Create High-Res, read more..
Our smiley face looks great on a standard display, but it’s pretty jagged on the Retina display. Figure 4-12 shows how our canvas image looks on the iPhone 3Gs and the iPhone 4. 178 HTML5 HACKS www.it-ebooks.info read more..
Our code simply draws out this smiley face on the lefthand side of the tag. For illustration purposes, a 1 px border has been added to the tag so that we can see the boundaries (see Figure 4-15). Going back to our three-step process, once we draw our illustration we need to erase what we’ve drawn: For simplicity I’m erasing the whole canvas, but read more..
Figure 4-15. The smiley face illustration on the lefthand side of an 800-point canvas Figure 4-16. The 800 × 2 00 <canvas> tag after the clearRect method has cleared the entire canvas context 184 HTML5 HACKS www.it-ebooks.info read more..
Now, for step 3 we will redraw our smiley face, but we will move it slightly to the right. In order to do this, we will move the position of both our methods and our element start position ( in this case). To accomplish this, we will replace each number with a simple equation to generate the proper x coordinate each time the element is read more..
We want to put a little bit of pep in this animation, so we will create a new variable called and set it to . When this number is added to the current position, it will move the smiley face forward or back six pixels, thus increasing the speed. Let’s look at the code: Implementing requestAnimationFrame As mentioned earlier, is a new read more..
187 CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG www.it-ebooks.info read more..
HACK 42 Figure 4-17 shows a snapshot from our example. Our smiley face starts at the far-left side of the canvas element, and then animates to the far-right side. It will then repeat this step over and over again. Figure 4-17. A frame from the smiley face animation showing the smiley face moving from one side of the canvas element to the other and back read more..
itself. Being an XML-based language, SVG doesn’t require an editing program like Flash, Photoshop, or even Paint. You can create and edit SVG images with any simple text editor, or with your favorite web editor. The S in SVG stands for Scalable, and scalable it is! SVG is resolution-independent. Your SVG images can be zoomed in or out, and even printed at any read more..
Figure 4-18. The smiley face SVG image represented in our sample web page template This first element is the yellow circle that represents the head of the smiley face. As you can glean from the preceding code, the element is actually a element that has attributes representing the following: , These are the and positions of the circle as it relates to read more..
This is only necessary when you have a stroke declared. As is obvious in the at- tribute name, this declares the width of the stroke in points. The default is . The next two elements are the eyes of the smiley face. They contain many of the same attributes as the previous circle. The two circles are identical to each other except for the read more..
HACK 43 This references the DOM for the clip path within our SGV file. When we refer- ence the clip path, the shape gets applied to this element, in a manner that clips off anything (fill or stroke) within the image. We could have drawn a line for the mouth of the smiley face, but it would have been a lot more work to draw out that shape in read more..
SVG has the ability to control the presentation of its elements by setting attributes on the elements themselves. Here are some of the more popular presentation attributes in SVG: • • • • • • • , • , • • • • Many times it makes sense to embed these attributes within the SVG itself where it can be downloaded as one file. Other times it read more..
This simple code snippet gets stored in a file called smiley.svg and embedded into our page with an tag as follows: Once the object is on the page, we see the SVG image as it should appear (see Figure 4-19). Figure 4-19. SVG representation of a smiley face Stripping Away the Noise In order to move our visual aspects of the illustration to CSS, we read more..
I want to point out a few things about the preceding SVG code. First, note the element with the class of . We have inserted a and of . At the time of this writing, current implementations of clip boxes require some and attributes set in the element to take effect. Second, I have added a attribute to each element and assigned at least one read more..
In the preceding example we have a few simple class names, such as and . If we write CSS declarations based on these class names and put them in our master stylesheet, they won’t actually affect our SVG elements, as the CSS will not cascade down to the SVG elements. To resolve this issue we need to load our CSS in one of three ways. The read more..
That was simple enough. The second factor to address is positioning. In order to not have all our elements stacked up on top of one another, we need to tell them where to go. For this, we will pull out one of our new CSS3 attributes called , which we will use to move our elements into place. Here is a sample of our CSS3 transforms within read more..
For more information on how the clip path works, see Hack #42 where we clarify how and why we use clip paths. With this CSS, our finished product looks identical to the one we started with where all our attributes were directly within the SVG elements. Figure 4-21 shows our finished product. 198 HTML5 HACKS www.it-ebooks.info read more..
Figure 4-22. SVG elements without any animation From this code we end up with a rectangle with a circle inside it (see Figure 4-22). In order to animate this ball moving from one side of the rectangle to the other, we will add a new tag and nest it inside the element, as a child element (think of it as a command associated with the element). Let’s read more..
This new tag allows us to animate the element while all other elements stay fixed. In this tag we are utilizing three attributes: The path is the hardest part of this tag. It appears to be a random list of numbers and letters that somehow give us a perfect path from one end of the rectangle to the other. This path is actually a wrap-up of our read more..
Figure 4-23. SVG animating the ball back and forth inside the box with only one line of code Flexibility in Structure In our first example, we made the tag a child tag to the element that was being animated. In many cases you may have a group of tags that you want to animate. To address such situations we will pull out some code from a read more..
Here is our second sample: In the first sample we had a parent element to our code, named , which is code for “group”. On ce we group our code together, it’s treated as one element (on that level) and our tag simply becomes another child tag to the element whose job is to animate the group of elements. In the second sample, instead of read more..
HACK 45 Keeping in mind that SVG elements become DOM elements just like any other HTML page elements, we can animate our SVG just as we would HTML, by using CSS. In the preceding sample that introduced the element, we can remove the tag completely, and set an on the element. From here, we can use a CSS3 transform to create the same read more..
In the preceding example, once the renderer sees the SVG declaration tag it switches parsers from HTML to SVG. When the tag closes it goes back from SVG to HTML. Our results look exactly as they did when the SVG was in an external file (see Figure 4-24). Figure 4-24. The SVG smiley face illustration where the SVG is inline with the HTML 205 CHAPTER 4: read more..
Why Inline? Aside from the obvious “ease of use” argument, there are additional benefits to putting your SVG inline. Above all, inline SVG can be used as a performance enhance- ment. In some scenarios, you may benefit from not having to load the external file (as it will require an additional call to your server) and can put the SVG code directly in the page. read more..
Figure 4-25. An SVG smiley face, loaded as an external .svg file Figure 4-26. An SVG smiley face, loaded inline in the HTML document 207 CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG www.it-ebooks.info read more..
As you can see, the CSS applies to none of the circles within our embedded SVG and to every circle within our inline SVG. Embedded SVG may not always be the best choice for your documents, but it’s always nice to have options. 208 HTML5 HACKS www.it-ebooks.info read more..
5 User Interactions It may seem like HTML5 has a lot to do with how things work under the covers. We discussed a new way to draw, a new way to present imagery, a new way to perform animation, new ways to store data, and new ways to talk to the server. This chapter focuses on a different aspect of HTML5: the new way you interact with the page. read more..
HACK 46 the World Wide Web the “web” that it is t oday. With HTML5 history, you can make your own history just within the page you are on. No longer do you need to rely on hash map tricks. HTML5 also gives you full control of those buttons. As an application de- veloper, you decide what happens when users click the history button while they are on your read more..
Figure 5-1. Shortcut formed when dragging a link to the desktop Images have a similar behavior. Since an image tag is tied directly to a file, it can be dragged as well. Keep in mind that not every image in a web application is an image tag. Many images are embedded in CSS with background images, or are created through SVG or canvas tags. This inherent read more..
Figure 5-2. Copy of the image dragged to the desktop It’s pretty simple, and when we add the CSS, we get what’s shown in Figure 5-3. Figure 5-3. Two draggable components and one target div 212 HTML5 HACKS www.it-ebooks.info read more..
At this point we can pick up the targets and drag them around the page, but as soon as we drop them they skulk back to their original positions. Without any listeners to catch what’s going on, there isn’t much to hack about. Now let’s look at our events. Listening for All Those Great Events HTML5 really does take DOM (Document Object Model) events read more..
HACK 47 Here we have added a little bit of additional context to the elements while they are being dragged, to emphasize which element is being moved. In this case, when we start dragging our circle we change the border to a pink dotted line, and when we finish dragging we add a to the to make it look like it vanished from the DOM. Remember, read more..
Figure 5-4. Page while draggable circle is dragged on top of our simple garbage can Many times you drag an element because you want to move it to another place on the page. This requires that your dragged item and your drop zone be able to communi- cate the appropriate information. Luckily, HTML5 has an API for that! For this hack we will start with read more..
Note that our s styled as colorful balls all have the attribute of set to . This enables them to be dragged around the page. Events play a big part in this interaction (for more information on events that are published while dragging and dropping, read “Make Any Content Draggable Within Your Application”). To grab hold of the events that are being published read more..
Figure 5-5. Single draggable div element being dragged over the drop zone Incoming: Data Transfer Object At this point, you may not be satisfied with this hack: you’ve probably figured out that you can drag an item just fine, but this capability isn’t very impressive if you can’t drop the item somewhere. We want the colorful ball s to change position in the read more..
All we really did here was add a single line of code. We set the MIME type to text (since we are passing a string), and then we have the item pass data about itself—in this case, its class name. We will use the class name to identify the object in the DOM. Publishing data isn’t very useful if there isn’t anything reading it. So our next read more..
The functionality is fairly simple. We use the class name we pulled from the data transfer object to find our dragging element in the DOM. We then do a simple to put that element inside the drop zone. Once it’s in the drop zone, our CSS kicks in to turn that colorful ball into a colorful flat line. After the drop, the drop zone looks like Figure read more..
HACK 48 Don’t get too excited—by no means does adding this attribute make this any more of a drop zone than it already was. We still need our listeners for that. Rather, this attribute provides additional information and makes our page that much more accessible. Drag Files In and Out of Your Web Application No longer are you constrained by the limits of read more..
Figure 5-7. Three divs rendered as colorful balls, all tied to files in the cloud Let’s dig into our attributes here a bit. The first attribute we have on each is the attribute, set to . This is a foundational attribute for drag-and-drop because it allows us to be able to pick the element out of the page and drag it around. Some elements, read more..
Let’s walk through what is going on here. The listeners are attaching to the event. The event is important in this process because it is the only point in a drag-and-drop when you can add data to the object. (For more about the data transfer object, see Hack #47 .) In this case, we attach a listener that fires the function. This function has only read more..
Instead of getting a “not allowed” symbol when we drag, we get a pointer symbol telling us all is well in the drag-and-drop world. Even better, once we drop the element outside the browser window, we see that text file from the cloud appear in our OS filesystem (in this case, the desktop). It’s drag-and-drop magic! Bringing Files Back to the Browser Wow, read more..
This function seems relatively complex compared to the one line of code that it took to bring the file down to our desktop, so let’s walk through what is going on. The first thing we have to do is to stop the browser from trying to load the file in the browser window. We have two methods that we call for that, as some browsers require read more..
Not everything that is dragged and dropped in the window is a file, so the next step is to check to see if we are uploading a file; if we are, the length of this array will be at least 1. We will wrap the rest of our code in this condition, because if there isn’t a file in the drag, there is nothing else to do: For the next step read more..
HACK 49 Figure 5-9. Text area after the text file from the desktop is dragged to it There are endless possibilities as to what you can do with local files once you get them into the browser. In this case, I can upload that data to the server, or I can edit it some more and drag it locally again. HTML5 brings the functionality that used to be limited read more..
The preceding markup is the main content for our page and the results should look like Figure 5-10. Figure 5-10. Our content inside an HTML5 page You may have noticed the new attribute on our container that says ; this attribute is all we need to make our content user-customizable. Just as though they were typing in a text area, our users can now edit this read more..
is smart enough to know what part of the markup they are editing, and matches their new content to the elements they are in. For example, if the user is in an unordered list ( ) and presses Return she will add another to the list. Pressing Return inside a paragraph creates a new paragraph, and so on. Now, at this point, if the user refreshes the page read more..
HACK 50 Spellcial! Another nice feature that comes with editable content is spellcheck. That’s right, built- in spellcheck. Much like you are used to in your desktop word processor, if you misspell a word in HTML5, a squiggly line appears underneath it, and if you right-click on that word you can choose a replacement word from the browser’s built-in dictionary. If read more..
Figure 5-11. Page before any content is edited, and with design mode off We will use the controls we added to turn our document’s design mode off and on, and to export the code. Let’s look at the markup for our page controls: We basically have text, two buttons, and a text area. The buttons will need listeners to have functionality. Let’s look at read more..
HACK 51 We can now make our edits directly in our web page. Keep in mind that we are editing text on the page; we cannot resize or reposition elements. But we don’t have to worry that our page will not render the same way it appears in our editor, since our rendered page has become our editor! Take Control of the Browser History Buttons with read more..
Figure 5-13. Page with missing content Here we have entered five new entries into our history stack. At this point, if we re- freshed our page we could click the back button five times before it would take us back to the previous website. However, nothing would change about the page when we click the back button. For that we need to set up a read more..
Inside this method we actually see a statement. This statement is used to determine which step of our process is being called on each time the back button is clicked, and what method will be fired to handle the functionality. If you look back at when we added the entries to the history stack, you will see each of them went in with a value name and read more..
Each phase draws something new. If we again refresh the page and click the back button, we will now see a yellow circle on the page (see Figure 5-14). Figure 5-14. Our web page after the back button is clicked one time If we continue to click the back button, the smile will be drawn, then the right eye, and then the left eye. After clicking the read more..
Figure 5-15. Our web page after the back button is clicked four times If you have a keen eye, you may have noticed that we clicked the back button four times but we put five entries in the history stack. You may think you still have one additional back button click on this page before you would go back to the previous page. You would be wrong. read more..
Goes forward by one step. Pushes the data specified in the arguments onto the session history. Updates the current entry in the session history. 237 CHAPTER 5: USER INTERACTIONS www.it-ebooks.info read more..
www.it-ebooks.info read more..
HACK 52 6 Client-Side Data Storage Hacks As the modern web browser continues to evolve into a capable application platform, another area of exciting advancements is occurring in client-side data storage, most notably in the AppCache, WebStorage, IndexedDB, and FileSystem API standards. The need for offline capabilities and performance improvements for reading and writ- ing large read more..
applications, it is also often advantageous to reduce the number of HTTP requests by embedding smaller images within a page. Furthermore, instances where you may want to dynamically generate server-side images based on a unique profile, time of day, or location of a site visitor may also warrant an embedded image. Data URLs utilize the following syntax: Within an read more..
Within an External Stylesheet Now we’ll use the syntax within a CSS selector, much like we would when calling an external background image: Don’t forget your respective markup tag: Figure 6-2 shows the results. Figure 6-2. Inline image in the document, and a repeated background image within the stylesheet See Hack #19 for more information on using data URIs within read more..
Grails Via the Grails Rendering Plugin: In the view: Node.js By setting up a route and creating a buffer, with the second argument as followed by a Base64-encoded string conversion: 242 HTML5 HACKS www.it-ebooks.info read more..
Ruby On Rails (via the Asset Pipeline) By using the helper: Django By using a simple Django filter, such as the one mentioned at djangosnippets.org: Disadvantages to Using Data URLs There are some disadvantages to using data URLs, namely the following: Caching The browser will not cache inline images that use data URLs to store their Base64- encoded data. If an read more..
HACK 53 File size A Base64-encoded image is one-third larger than an equivalent binary image. Again, you will need to decide on this balance based on given user behavior and traffic patterns. Convert a Data URI to a Blob and Append It to Form Data with XHR2 HTML5 has turned the web browser into a full-fledged runtime. With all that new functionality in the client, you read more..
There are a few important items to notice here. The attribute indicates that the data will need to be chunked into a multipart data item. Also notice that we are making use of a few new attributes: and , mentioned in Chapter 1. The requirements for our application also include uploading an image to a separate remote web service. The image is available as read more..
HACK 54 Once we pass the reference into our function we check to see if it is , and unescape it if necessary. Then we set a reference to the MIME type, write the bytes of the string to an , and pass the to a new , along with the MIME value set to the property. Now, we generate the new and append the as a : Use the WebStorage read more..
Data persistence in the early days of web applications relied on one basic technology: cookies. Although cookies were serviceable, they were burdened by privacy concerns and limitations (in terms of storage size and their impact on network performance). Luckily, HTML5 provides a much-improved way to handle persistent data storage: LocalStorage. Technically called the read more..
• • • • I’d be willing to bet you can figure out what the first two do. The third, , allows you to completely remove a value from LocalStorage. And lastly, will remove all values. Again, though, remember that operations on LocalStorage are domain-specific. Calling while visiting foo.com will not clear the items that had been set at goo.com. Let’s read more..
This template fires off a simple function, , when the page has loaded. We begin by seeing if the key exists in . If it doesn’t, we default it to . Next we get and increment the value. Since everything is stored as a string, we wrap the call in the constructor to ensure that the math operation works. We then update the DOM and display the read more..
250 HTML5 HACKS www.it-ebooks.info read more..
HACK 55 Polyfill LocalStorage with YepNope.js and Storage.js Although the WebStorage API is widely supported across major browsers, there is still a need for polyfill support in IE 7. One of the most popular and easy-to-use polyfill script loaders is YepNope.js. Remy Sharp defines polyfills as follows: A polyfill, or polyfiller, is a piece of code (or plugin) that provides read more..
1 http://yepnopejs.com/ Figure 6-3. Modernizr object in Chrome console Modernizr includes YepNope.js as an option for conditionally loading external .js and .css resources. This is quite handy for managing the support of polyfills within your application. Using YepNope YepNope is described as “an asynchronous conditional resource loader that’s super- fast, and allows you to load read more..
Using Storage.js Storage.js is a library written by Brett Wejrowski. The script uses for IE 6 and 7 and for Firefox versions 2 and 3 to implement a polyfill for when it is not supported. You can view the contents of the storage.js file on GitHub. To demonstrate the effectiveness of our polyfill loader, we will implement a simple counter that stores read more..
HACK 56 Figure 6-4 shows the results. Figure 6-4. Clicks counter stored in LocalStorage Cache Media Resources Locally with the FileSystem API With the FileSystem API, you can provide your browser with a sandbox where data (both textual and binary) can be read and written. This hack was contributed by Raymond Camden, a senior developer evangelist for Adobe Systems Inc. 255 read more..
One of the more powerful features coming soon to a browser near you is the ability to read and write to the local filesystem. You can find the “File API: Directories and Sys- tem” working draft on the W3C website. Dubbed the FileSystem API, it provides the browser a safe little sandbox where data (both textual and binary) can be read and written. Many read more..
Note that you have requested a size, but it’s possible the size given may be smaller. Don’t even worry about what you’re given for now. In the future, you may want to record this ( ) and ensure you stay within your quota. But the important thing to note here is that once you’ve been approved a bucket of space you can request the actual read more..
The preceding code was taken (and slightly modified) from the HTML5 Rocks arti- cle. It’s just for testing and doesn’t actually present any nice response to the user. It only uses the console to report errors. Be sure you do your testing with the console open. Working with the Filesystem So, at this point we’ve established that our browser supports a filesystem. read more..
First, let’s open this directory. The API allows us to open a directory that doesn’t exist. We do this by passing a flag. We can only do this for one level of directory at a time. So, for example, we can’t try to open /resources/images/highres and have the API simply create all those nested folders. In a case like that, we need to read more..
The first portion of the preceding code block executes if we have a value for when the ZIP file was last modified. (Soon we will see where to set that.) If exists, we create a -only Ajax request. This is a lightweight network call that just returns the headers of the remote resource. We check the header. If it is different in any way, we read more..
The very first thing we do is cache the date the ZIP file was modified. LocalStorage makes this incredibly easy to do. Make note of the key. We can test the code multiple times. We can either build new ZIP files and update their last modified value via the command line, or simply use our browser’s console to de- lete the value. Next, we’ll read more..
Then, opens the file on the filesystem. Within the success handler, we can use entry, which is the file in the ZIP file, and pull the data out with . Essentially, we open a file on the filesystem and siphon out the bits from the ZIP file entry into the file we opened. The first argument to is a file writer. That han- dles the actual bits. Two read more..
Figure 6-7. HTML5 FileSystem Explorer (seen in the top-righthand corner), which browses the filesystem asso- ciated with a website After the user clicks on a button, the code loops over an array of filenames to see if they exist in the filesystem. If so, the code simply adds an image to the DOM. Note the use of . I used this call to get a reference to read more..
HACK 57 Where to Go from Here I hope this hack gave you an idea of what you can do with the filesystem. While support is still somewhat limited, the benefits of being able to store resources locally make it more than worthwhile, even if the API is a work in progress. Keep your eye on the File API W3C working draft for updates. Build a Milestone Calendar read more..
Figure 6-9. Date pickers To instantiate the date pickers we will include the following toward the beginning of our script: The Milestone IndexedDB Now we will set up a global namespace to hold our code, and set up a public array (within the namespace) to hold our milestones temporarily while we pass them between our database and the FullCalendar API. This read more..
Now we can begin to set up our database: This will obviously fail for now, but as you can see the initialization begins by calling the method on an . So let’s take a closer look at : 267 CHAPTER 6: CLIENT-SIDE DATA STORAGE HACKS www.it-ebooks.info read more..
First, we need to open the database and pass a name. If the database successfully opens and a connection is made, the callback will be fired. Within the , we then check for a version and call if one does not exist. Then we will call and pass a unique timestamp within the property. Finally, we call to build the calendar and attach the events read more..
At this point we are poised to retrieve all the data from the database and populate our calendar with milestones. First, we declare the type of transaction to be a , set a reference to the , set a , and define a by calling and passing in the . By passing in a , we ensure that we retrieve all the values greater than zero. Since our key read more..
Adding Milestones Now that we are initializing and building our calendar, we need to begin adding mile- stones to the database via the form. First let’s use jQuery to set up our form to pass a serialized data object to on each submission: Now let’s submit a few events and then view them in the Chrome Inspector to ensure they are there (see Figure read more..
We established our read/write connection in much the same way as our , but now, instead of only reading data, we write a data object to the data store each time by calling and passing it data. On the we then can call ’s and pass it the data wrapped in an array object. Note that it is necessary to transform the data object into an array read more..
www.it-ebooks.info read more..
7 Geolocation Hacks An exploration of the future of web technologies and browser capabilities would not be complete without covering the tools and techniques available to enable location awareness. Location-aware web applications provide content, functionality, and services based on the cooperative detection of the user’s physical location. These applications can then provide the read more..
HACK 58 •GPS • GSM/CDMA cell tower IDs Geolocation libraries for the Web are not new. In fact, today’s W3C Geolo- cation specification is largely reflective of the original Google Gears API in- troduced by Google in 2008. The API has been standardized and is one of the most widely adopted of the HTML5 specifications covered in this book. Fortunately, the API is read more..
A Simple jQuery Mobile App As always, we’ll start by building a basic page utilizing the HTML5 and including our dependencies: As you can see, we have declared a dependency on one stylesheet, and three Java- Scripts. We will build the remainder of the application using declarative HTML markup and attributes that the jQuery Mobile framework will interpret. read more..
At this point you should see what’s shown in Figure 7-1, if you access this page from a smaller screen or shrink your desktop browser window to the size of a mobile browser. Figure 7-1. jQuery Mobile simple button 276 HTML5 HACKS www.it-ebooks.info read more..
As you might expect, the UI wasn’t created through magic. jQuery Mobile uses Java- Script to consume the attributes present in your HTML markup to dynamically generate more HTML and CSS. The end result is what you see in your browser. Now we will create a separate page to link to. You many have noticed a link to longlat- embed.html within the read more..
1 http://dev.w3.org/geo/api/spec-source.html Now let’s return to our browser and navigate to the new page. When a user accesses a web page that includes a call to , a security notification bar will be presented at the top of the page. Browsers that support the Geolocation API have their own security notification, which asks the user to allow or deny the browser read more..
HACK 59 Figure 7-3. Latitude and longitude Use Google’s Geocoding API to Reverse- Geocode a User’s Location Longitude and latitude data is only beneficial to the application if it can do something more interesting than just display it. One common use case is to reverse-geocode, or find a human-readable location based on longitude and latitude. 280 HTML5 HACKS www.it-ebooks.info read more..
In Hack #58 we hacked together a simple mobile web application that displayed the user’s current longitude and latitude. In this hack we will use the same jQuery Mobile application and add an additional button to the home screen. This button will take us to a separate page that displays the nearest city and state based on our current location. First, let’s read more..
Figure 7-4. Adding a Location By Name button Now we will create a method that accepts the longitude and latitude that was returned by . First we’ll take our latitude and lon- gitude data and pass it to the helper function. Then we’ll set that value to the property of an empty object. 282 HTML5 HACKS www.it-ebooks.info read more..
The method will make a call to Google’s Geocoding API and return a large result set that contains more information than we need. Therefore, we will need to parse out the city and state from the result set. Our value is stored in a property named and the is stored in . The code for doing this follows; Figure 7-5 shows the result. 283 CHAPTER 7: read more..
Figure 7-5. Showing the location name Here is the final script: 284 HTML5 HACKS www.it-ebooks.info read more..
285 CHAPTER 7: GEOLOCATION HACKS www.it-ebooks.info read more..
HACK 60 Update a User’s Current Location in a Google Map Sometimes the user of your application is moving and a location needs to be updated at a regular interval. You can use a Google map to display a moving pin of the user’s locations. Using the Google Maps API In this hack we will start by including the necessary dependencies for displaying Google maps read more..
Figure 7-6 shows the result. In case this type of programming is new to you, the properties within are optional and configurable. The complete API reference is available online. Figure 7-6. Reverse-geocoding a location with Google’s Geocoding API 287 CHAPTER 7: GEOLOCATION HACKS www.it-ebooks.info read more..
Now that we have a working Google map, let’s start updating our map with a map pin. To do so, we will use to determine our location. Updating the Current Location with a Timer An application that can auto-update would obviously make our users’ lives easier, by not asking them to update their location as they move. To enable an auto-update, we will read more..
Improving the Map Everything else, including the code for our Google map, will reside in the callback that is called once the user has allowed her location to be determined, and the service has returned a longitude and latitude. The property is available within the callback object, so we will pull the latitude and longitude from there and pass it to the read more..
Figure 7-7. Placing a radius around the pin Improving Accuracy In the introduction to this chapter I listed a number of technologies (public IP address location, cell tower triangulation, GPS, WiFi/Bluetooth MAC addresses, and signal strengths) that a particular device can use to pass parameters to a Location Infor- mation Server to estimate a user’s location. The read more..
HACK 61 2 http://en.wikipedia.org/wiki/Geo-fence The attribute provides a hint that the application would like to receive the best possible results. This may result in slower response times or increased power consumption. The user might also deny this capability, or the device might not be able to provide more accurate results than if the flag wasn’t specified. Saving Power read more..
To demonstrate the fence we will then retrace our steps, and make a call to request the nearest tagged location. As we move back through the tagged locations, Geoloqi’s service will perform the necessary logic to determine which stored location is nearest to our current location. This is only a small portion of the Geoloqi API, as a complete exploration read more..
Figure 7-8. Creating a new application The form has three main purposes. The button with submits a new location to the Geoloqi service by making a call to . The second button returns the last location that was added. The third button returns the location nearest to our current location. To finish the necessary HTML markup for our interface we will also read more..
We also need to initialize the Geoloqi library and pass in the we re- ceived when we created our application at geoloqi.com: Next, as we have done in the other hacks in this chapter, we will use . Review those hacks if you want more detail, but here is the gist of it: Now let’s begin building our event handlers. First we need to create a read more..
To receive the last location we entered, we create the method: To get our nearest location within our geofence we use the following: Finally, to set up both a trigger (an event such as an SMS message or push notification) and a place in one call, we will create an object called a geonote that will be called when we get within 100 yards of read more..
This is just the beginning of what you can do with the Geolocation API and the Geoloqi service. Now, take this as inspiration and build a more ambitious hack! 297 CHAPTER 7: GEOLOCATION HACKS www.it-ebooks.info read more..
HACK 62 Use the Geoloqi Real-Time Streaming Service to Broadcast a Remote User’s Movement The combination of the Geolocation API and the Geoloqi Websockets server creates a world of opportunity for innovative hacks. The WebSocket Protocol’s full-duplex, bidirectional transport enables you to provide real-time updates of the remote user’s location on a map. The WebSocket read more..
Now we need to make sure we have the Geoloqi test account share token. We would obviously replace this with a real share token once we are ready to implement it with real users. If we open the console, we will see objects being logged in the console (as shown in Figure 7-10). Figure 7-10. Google Chrome Developer Console viewing Geoloqi trip event objects read more..
These objects contain information related to the location of the user with a shared token each time our application polls for a location. First we will include the element with : Now let’s add a Google map to display the user’s location. In Hack #60 we discuss using the Google Maps API in more detail. For this hack we will keep the map simple. read more..
Now we should see the pin moving on the map in real time, in sync with the remote user we are tracking. To test it yourself create an account and replace the token with your own. The result should look like Figure 7-11. Figure 7-11. Google map pin of a remote user updating in real time For more information about Geoloqi socket streaming, visit the read more..
HACK 63 Polyfill Geolocation APIs with Webshims Often, web application developers are tasked with achieving cross-browser compli- ance with the functionality they are targeting within an application. The Geolocation API is not available natively in IE 8 and earlier, but there are alternative polyfills, such as webshims, that you can use to get the job done. I have included read more..
When we refresh a browser that lacks geolocation support, such as IE 8 and earlier, we should see the alert. So, now we can remove it and replace it with our webshims script. First we will set up an option, , to configure the message displayed to the user. Then we will call and pass in the features we want to add. For this hack, we will read more..
And here it is, all together: 304 HTML5 HACKS www.it-ebooks.info read more..
305 CHAPTER 7: GEOLOCATION HACKS www.it-ebooks.info read more..
www.it-ebooks.info read more..
8 WebWorker API The WebWorker API provides a simple set of methods for web content to run scripts in background threads. Web workers are executed from a main browser window but run independently and in parallel. Once a script in the main thread spawns a worker, the worker can send messages back by posting them to a defined event handler. Data is serialized, not read more..
HACK 64 Use the BlobBuilder Interface to Create an Inline Worker Sometimes developers need to keep scripts and markup together in one HTML file. When necessary, you can create an inline worker with the BlobBuilder interface. This hack will teach you how to parse batched Facebook data. As I mentioned in this chapter’s introduction, there are three types of web workers: read more..
The Facebook Graph API and Batching Responses Often it is desirable to reduce an application’s HTTP requests to as few as possible, if not a single request. In this hack we want to fetch data from the fan pages of a large number of bands within a particular genre. The data we are interested in is the property. This property is a metric that is read more..
Figure 8-2. Facebook Graph API’s batch support Building the Blob First we will use a fairly common approach to fetch the worker content from our inline worker and append it to a . We’ll use the following vendor-specific methods: Now we’ll grab the content using the method and the property of our selected element: Finally, we need to create a and a read more..
Fetching Data from the Facebook Graph API Now we can fetch the data we need by calling the public Facebook Graph API. So first we will set our URL, making sure is set to to overcome the cross-domain problems with JSONP (more on JSONP in Hack #68 ): Next we will use jQuery’s method to make our object, serialize the response, and pass it read more..
Now we can set up our listener to respond to messages that come back from the worker. Once we get the data back from our worker thread we will handle it by updating our UI. First, let’s take a look at the data by examining it in the console. We should see that our data is now minimal, with only the and properties. Also, the bands should be read more..
HACK 65 Figure 8-5 shows the result. Figure 8-5. Top 10 list of Jam Bands by talking_about_count Perform Heavy Array Computations in a Dedicated Web Worker Dedicated web workers are a great solution for expensive computations such as array manipulation. With this hack you can move such a computation to a worker without impacting the performance of an interactive read more..
To begin to understand the power of web workers we need to manufacture an expen- sive operation, and create a UI that uses some type of animation that we would like the user to be able to interact with seamlessly. For the expensive operation we can manipulate array data, and for the animation we can create a simple canvas that has balls bouncing read more..
We also need to create a simple UI for demonstrating our worker test. So let’s create select boxes that contain the values we will pass to our computations. One select box will fire the function and the other will fire the function that will perform the same computation inside a worker (more on the function later in this chapter). We can also add read more..
Figure 8-6 shows the result. We also need to use jQuery to add a few event listeners to listen for click events on the select boxes. Our select boxes’ event handlers will be and , respectively. And finally, we will add an function that listens for the window’s event and initializes our scripts. 318 HTML5 HACKS www.it-ebooks.info read more..
Figure 8-6. Building the basic UI The Bouncing Balls Canvas Now let’s include the canvas animation. We’ll use a modified version of an existing canvas demo provided by Eric Rowell. For our purposes we just need an animation that we can interact with. First let’s add just a bit of style to our element: 319 CHAPTER 8: WEBWORKER API www.it-ebooks.info read more..
Now we can add the script. We won’t include Eric’s long script here, but you can see it in the companion Git repository. We should now have a fully functioning demonstration. As we begin to increase the size of the values in the select boxes and press the Without Web Worker button (see Figure 8-7), we should see the interaction among the balls in read more..
Spawning a Dedicated Web Worker The WebWorker API is straightforward and easy to get started with. First we will obtain the values from our select boxes and store them in the variables and . Then we will instantiate a new web worker by using the operator on the class and passing a URI that points to our worker script. 321 CHAPTER 8: WEBWORKER API read more..
Now we’ll craft an object to pass to our worker. As you will see in a moment, our worker will be organized as a library of methods. This object is actually a configuration object that has a property that instructs the worker library as to how to parse the data. We’ll then pass our data to the worker via . We also need to serialize our data read more..
Finally, here is our worker script in its entirety: Figure 8-8 shows the result. 324 HTML5 HACKS www.it-ebooks.info read more..
HACK 66 Figure 8-8. Processing complete Use a Timer to Send Application State to Workers The combination of timers and web workers opens new opportunities in the develop- ment of client-centric HTML5 applications. It is possible to make your application artificially intelligent (in a very basic way) by giving it a set of functions called at a regular interval. Although read more..
Figure 8-9. Angus Croll’s crazy flies In the hack we will explore very basic concepts of artificial intelligence by using Java- Script timers and random number generation to create a web-based visualization. One might argue that this is not artificial intelligence, but it is a basic simulation of intelligence demonstrating two main subproblems: localization (knowing where read more..
General Overview The general idea of this hack is to generate a number of elements and append them to the DOM. These elements will be icon elements that we will refer to as objects and we will append them to the tag. But first let’s set up a few objects to hold our data: Now we’ll define a class that we can instantiate when creating read more..
Now that we have set up our UI to give us some controls, let’s initiate our script by adding an event listener to the Generate Movement button, and a callback event han- dler called . will accept the value that was selected in the select box. 329 CHAPTER 8: WEBWORKER API www.it-ebooks.info read more..
Once is called, two things will happen. First, we will begin moving our Thing icons around in the viewport, and second, we will set up another click listener on an- other button that will start the timers. From now on we will call this our AI button. Let’s add the additional button: Figure 8-11 shows the basic UI. Now we can begin moving the s around read more..
Figure 8-11. Building the basic UI Now we’ll add another click event handler to the AI button that will start the timers: 331 CHAPTER 8: WEBWORKER API www.it-ebooks.info read more..
At this point we’re ready to add the timer calls that invoke workers on regular intervals. For now we will set the timers to 1000 ms or one second. We will set up four actions that will process our data in four different ways. You might be asking, “What is the curry function inside our s? What does the curry give us?” 332 HTML5 HACKS read more..
information, such as their x and y coordinates, and posts the data to a web worker library for processing. When the library has received the data, it will perform a com- putation on the data by utilizing the action function that was passed in with our curried function. Figure 8-12 shows the result. Figure 8-12. Generating movement The Worker Library As we read more..
335 CHAPTER 8: WEBWORKER API www.it-ebooks.info read more..
Now that our worker library has done the necessary processing it posts the data back to the main thread that has been listening for any new messages. Any new messages will trigger the event handler, which will make updates to the UI (see Figure 8-13). As you can see, numerous methods within our worker library are processing the data through array manipulations. read more..
Figure 8-13. Things being eliminated It is the same pattern as a simple JSON object. Now we need to use the array bracket syntax to call the method of choice from within the class. Remember, the name of the function was passed in from the main thread. Now we can manage calls to any method within our library with only one handler. 337 CHAPTER 8: read more..
HACK 67 Real-World Use As I mentioned in the introduction to this hack, the core concepts of this simple script bear enormous potential for real-world use. Here are a couple of ideas to get you started: • Offline analytics • CoBrowse, user shadowing solutions • Client-side image processing • Background s • Background read/write to local storage We will explore read more..
Figure 8-14. HTML5 logo Now we’ll build our processing function, which will apply our filter to the image data. Our function will accept the image we captured in the event and the x and y coordinates. Next, we need to create a canvas in memory that is the same size as the image we passed into the image we are capturing: 339 CHAPTER 8: WEBWORKER API read more..
Now we’ll copy the image into the canvas, and then extract its pixels: Here we are sending the pixels to a worker thread: At this point we need to register a handler to get the worker’s response. When we receive the response, we will create a local variable that we will use to put the image back into a context object. We will use the read more..
You may have noticed the debugging technique we can use. Since we cannot use a console API within a worker, we need to check the data type of the returned message in the event handler listening to any messages in the main thread. If the message is of type , we assume an error and log it. Here is the finished product: 341 CHAPTER 8: WEBWORKER API read more..
Finally, we need to create our grayscale filter within our worker script. Here, we will make a call to , which will process the image data, removing the necessary data to return a gray image. The dynamic magic occurs in the variable, which multiplies the x coordinate’s position within the formula to return image data that contains nothing more than read more..
Figure 8-16. Right-side mouseover event resulting in lighter grayscale Then we will set up a listener for any messages passed back to our main thread. Within our listener, we will loop through the response and build a for each result. In the process, we will also append the profile image, and the name of the Twitter user that posted the tweet. 344 HTML5 HACKS read more..
But we are getting ahead of ourselves, so first let’s make the request to Twitter from within our worker. Our worker script is fairly straightforward. We need to set up a callback function that we will pass within our request to Twitter. Within our callback, we will simply pass the object back to the main thread to build out the UI. Later, read more..
Figure 8-17. Fetching the latest HTML5-related Twitter data Figure 8-17 shows the result. 346 HTML5 HACKS www.it-ebooks.info read more..
HACK 69 As I mentioned before, this is a very simple example. This approach can be very effi- cient for processing API data within a web worker. Often, developers will want to alter the format of the data within the worker, and then pass composites or even smaller portions of the original data back to the main thread. Now you can, too. Connect to Shared read more..
In each document being loaded in the s, we will instantiate new objects that point to the same external script. The event handler will expect two items as a response: a number that is maintained by a counter with the worker thread, and a randomly generated color that will be set as the background color of the document that spawned the worker. Figure 8-18 read more..
Figure 8-18. Including three additional iframes 349 CHAPTER 8: WEBWORKER API www.it-ebooks.info read more..
Figure 8-19. Random background colors for each worker spawned 350 HTML5 HACKS www.it-ebooks.info read more..
HACK 70 obsolete, but they do complement existing technologies by providing another tool for web application developers to use when building solutions that need real-time data updates. In fact, XHR has evolved into the Level 2 specification, which we got a taste of in Hack #53 . In Hack #75 I also will introduce the evolution of cross-domain communication as we read more..
We also need to add a tag with . This will be where we log our messages. The class has four public methods— , , , and —and one public property, . The property will hold the instantiation of our new object. Now, let’s take a look at the method. In we pass a URL as the only parameter. It is then passed to the instantiation of a read more..
Within the method we have also included a that will log the event type (see Figure 9-1). Figure 9-1. Logging the connection onOpen event To establish a WebSocket connection, the client and server upgrade from HTTP to the WebSocket Protocol during their initial handshake. There are several handshake mechanisms, but unless you are writing server-side socket implementations, read more..
Using the Google Chrome Developer Tools you can inspect this client/server interac- tion. Click on the Network tab and select “echo.websocket.org” on the left to see the request and response header information (see Figure 9-2). Figure 9-2. Inspecting web socket request and response headers You will notice in the request headers that there is a Connection: Upgrade header. You read more..
Now, let’s evolve our code a bit, and begin to add a few more public methods that will expose more connection events effectively demonstrating the internals of the socket communication: and . And in our , let’s execute our new methods: Now, if we refresh the browser we should see new console logs coming from our new event methods. The send call within read more..
Figure 9-3. Console logs from event methods 4. Select “echo.websocket.org.” 5. Select the WebSocket Frames tab. The information given is very beneficial and prevents you from having to install a third- party tool: Number This is a counter, to demonstrate the sequence of the messages. Arrow This is the direction of the message. Timestamp This is the time the message was read more..
Length This is the number of characters in the payload. Contents This is the actual data in the WebSocket payload. Figure 9-4 shows web traffic viewed with the WebSocket Frames tab in Canary. Figure 9-4. Viewing web traffic with the WebSocket Frames tab in Canary For clarity, let’s recap the interaction: 1. The client browser instantiates a new object and passes it read more..
7. The event method logs the payload to the client console and then calls . 8. The event method fires and logs and the event type to the console. Here is the final code in its entirety. This is just the beginning of a well-organized Java- Script WebSocket library. Take it and start your own hacks! 359 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
HACK 71 Build a Blazing-Fast WebSocket Server with Node.js and the ws Module The Node.js module is an easy-to-use, blazing-fast and up-to-date web socket im- plementation that you can use to get web sockets up and running quickly. It also ships with wscat, a command utility that can act as a client or server. In this hack we will explore the fastest WebSocket read more..
If you would like to get into the gory details of the WebSocket HyBi protocol, here are a couple of great resources to get you started: • http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 • http://updates.html5rocks.com/2011/08/What-s-different-in-the- new-WebSocket-protocol also ships with a nice command-line client called wscat, which will give us a tool for making and read more..
Figure 9-5. Using the Terminal to install the Node.js ws module Now, watch as NPM downloads and installs the module and all the necessary de- pendencies. At this point we should be able to immediately use wscat to send a request to the remote echo server hosted by Kaazing (see Figure 9-6): There we have it. Our command-line utility is up and read more..
Figure 9-6. Using the Terminal to make a request to the Kaazing echo server Now, that was one way to create a file. You could very easily just use your own way of doing it. If you are more comfortable using your OS’s GUI to access the filesystem, navigate to your empty directory, open a simple text editor, and create a file named server.js. In read more..
Now we save the file, and start the server: In another Terminal window we can use the wscat client to access our own server running on port 8080 (see Figure 9-7). And we receive our message. Figure 9-7. Connecting to the ws server from a separate Terminal And finally we can send a message back to the server by manually typing into the command-line read more..
Figure 9-8. Sending a message back to the server Now, switch back to the other tab, where the server is running, to see the message from the client (see Figure 9-9). The socket server is listening and logs : Creating a Simple Client Instead of interacting with our WebSocket Server via the wscat command-line inter- face, let’s write a script that will handle the read more..
Figure 9-9. Node.js server logging the message from the client terminal Let’s start the client: 366 HTML5 HACKS www.it-ebooks.info read more..
HACK 72 On the open event the message is sent to the remote echo server. The remote server then returns the message. The client is listening for messages and logs the response with . There you have it. You now have a great example of a WebSocket Server running locally, and a command-line interface to create and listen for web socket messages without a browser. read more..
4. Use Pusher to make the widget update in real time as new donations come in. Building the Thermometer HTML For accessibility it’s good to have some textual values, so for the HTML we’ll focus on that while adding some elements for the visual display. This creates a really simple display, as shown in Figure 9-10. This isn’t very exciting, but it displays read more..
Figure 9-10. Basic display 369 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
It’s worth providing a bit of information regarding the structure of the HTML: We saw this previously. It contains the key values for the widget. This is the visual thermometer display. This has the following values: This is the round bulb at the bottom of the thermometer. This can be used to show the textual value of the funds that have been raised. This read more..
Figure 9-11. Basic display with CSS When we generate the HTML we can then put an inline style on the element. The HTML will look as follows: This results in the thermometer visualization actually indicating a value, as shown in Figure 9-12. 371 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
In the following code we reference the and and get their height. We access the charity goal amount and current total from the UI and parse out the values using the function. Using all this information, we know how many marks we are going to add to the element. Then we add the ele- ments that represent the marks. There is a bit of setup here read more..
It would be nicer if the markers were at more rounded values, but I’m not trying to build a real product, just show what’s possible. This results in the thermometer display shown in Figure 9-13. Figure 9-13. Adding markers 374 HTML5 HACKS www.it-ebooks.info read more..
Marker Values, Hover Highlights, and Tool Tips The thermometer markings aren’t of much use if we don’t know what values they represent, so let’s display the values when the user hovers over the marker elements by displaying a tool tip. We’ll also add a small highlight effect. You’ll see from the pre- ceding piece of code that we already got elements, read more..
Figure 9-14. Marker values, hover highlights, and tool tips Animating Value Changes The final effect that we can add is to animate the thermometer’s height and the textual values by increasing them from 0 to the current total. Let’s get a utility function out of the way. The following adds commas to values: 376 HTML5 HACKS www.it-ebooks.info read more..
Next, let’s animate the text. This is really just a visual thing. It doesn’t need to be too clever, so we’ll just increment the value every 50 ms by a calculated amount. We’re also going to return the identifier so that it can be cleared elsewhere if required. See mozilla.org for information on as an alternative to for animations. Now let’s animate read more..
Finally, let’s link up all these functions and fully stylize and animate the thermometer. We’ll also shift some of the comment setup calls into an function. 378 HTML5 HACKS www.it-ebooks.info read more..
The function returns the animation interval, which gives us the opportunity to cancel an ongoing animation if a new update comes in. This stops two animations running at the same time, where we can see some really crazy things. We’re now ready to create the code that triggers the update. We’re going to use PHP, and the Pusher PHP library by Squeeks for read more..
The config.php contains the database details. Now let’s add the real-time magic. All we have to do is to include the Pusher PHP library, create a instance, put the data we want to send into an array, and trigger the event by calling . The variables passed into the Pusher constructor are defined in config.php. 381 CHAPTER 9: HACKING HTML5 CONNECTIVITY read more..
That’s it! It’s really that easy to trigger a real-time event. And since we’ve done all the hard work on the client, the real-time charity thermometer updates in real time. Be- cause the PHP is taking values from a request, we can test the functionality by navigating to our PHP file, which we’ll call donate.php, passing the required query string read more..
jWebSocket is free and open source. One of its major benefits is that it comes with a powerful core that you can easily extend via plug-ins and web socket applications for up to hundreds of thousands of concurrent connections. SSL encryption and a mes- sage filter system provide a high level of security. Due to the standardization of the IETF and the W3C, read more..
The jWebSocketServer-<version>.jar file in the /bin folder includes all required libra- ries and provides the ready-to-use folder structure. It can easily be started from the shell or command-line window without any installation or special configuration. • For Windows: jWebSocketServer.bat • For Linux: jWebSocketServer.sh • For Mac OS X: jWebSocketServer.command Like normal read more..
This makes jWebSocket available to your page. You can use either the full inline doc- umented source code in jWebSocket.js, which is the best choice for learning jWeb- Socket, or the minified version in jWebSocket_min.js recommended for your produc- tion system. Creating the jWebSocketClient instance jWebSocket provides the class within the jWebSocket- specific namespace . This read more..
The server assigns a unique ID to the client so that a certain client can always be uniquely addressed even if the same user logs in at multiple browser instances. Sending and Broadcasting Tokens If the connection was successfully established the client sends its messages via the method to another client, or broadcasts it to all connected clients by using the read more..
You will find the full reference to the token set in the online developer guide. Logging Off and Disconnecting On demand, both the server and the client can terminate an existing connection. On the client side this is done by the method of the . The server automatically terminates the connection after a certain period of inactivity on the line. In this case read more..
Create a server-side plug-in The first step to extend the functionality of the jWebSocket Server is to create a server- side plug-in. A plug-in usually is implemented as a descendant of the class, which is included in jWebSocket. To develop your own plug-ins it is recom- mended that you create them in separate packages. This will make it easier to dis- read more..
390 HTML5 HACKS www.it-ebooks.info read more..
Add your plug-in to the jWebSocket Server The following listing demonstrates how to add your new plug-in to the plug-in chain of the jWebSocket Server: The class loads and starts the jWebSocket Server, including all its required libraries, default plug-ins, and filters. First the is obtained by its , which is configured in the jWebSocket.xml configuration file. read more..
Use the plug-ins in your web pages The final action to make the plug-in capabilities available to your application is to add a link to your new client plug-in to your web page(s): Included jWebSocket Plug-Ins jWebSocket already comes with a huge and continuously growing set of ready-to-use plug-ins. Table 9-1 gives a quick overview. 392 HTML5 HACKS www.it-ebooks.info read more..
Table 9-1. Plug-ins included with jWebSocket PLUG-IN PURPOSE API-Plug-in Publishing WebSocket APIs, such as WSDL for Web Services Arduino-Plug-in Hardware remote control and monitoring with Arduino Benchmark-Plug-in Speed measurement and communication profiling support Channel-Plug-in Implementation of the Channel-based communication model Chat-Plug-In Support for chat rooms, group and private real-time read more..
Although learning Ruby is another learning curve, in the larger scheme of program- ming languages it is a less daunting curve than most. And as most die-hard Rubyists will preach, it is arguably the most elegant and fun to write of all modern programming languages. Ruby on Rails, and its little brother Sinatra, are also great web application frameworks to read more..
As I said before, you can just follow the instructions at the Git repository to pull down and build this code. Or if you have been following along, launch a Terminal, navigate to the directory where your code is, and run the following: Figure 9-15 shows the Sinatra server starting up. Figure 9-15. Starting the Sinatra server All right, now we have our read more..
Setting Up the HTML Pages We will be building two pages: one for the admin to push out notifications, and the other for the connected receivers to receive the notifications. Both of these “views” will share the same layout, as shown here: The admin page will contain an tag and a simple button: Our receiver pages will display a simple piece of text: By read more..
Figure 9-16. The initial admin page Navigate to http://localhost:4567 in your browser and you should see what’s shown in Figure 9-17. 399 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
Now we can add a simple notification with the available data: And here is the final script for the admin: Installing jQuery.notify For our push notifications we will use Eric Hynds’ great jQuery plug-in, jQuery-notify. In order to display the notification, we’ll need to include some markup on the receiver page: This creates a hidden tag in the bottom of the read more..
Figure 9-19. Hidden div tag In order for jQuery.notify to initialize, we must first call the following: Here is the final script for the receiver: It’s that simple. The EventSource API is minimal and plugging it into a web framework such as Sinatra or Node.js is straightforward. 403 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
HACK 75 Now, as we submit notifications from the admin page, our receiver pages are updated with timestamped notifications, as shown in Figure 9-20. Figure 9-20. Pushing notifications to the connected browsers Configure Amazon S3 for Cross-Origin Resource Sharing to Host a Web Font Cross-Origin Resource Sharing (CORS) is a specification that allows applications to make read more..
1 http://en.wikipedia.org/wiki/Same_origin_policy Figure 9-22. Creating an S3 bucket in the S3 Management Console Well, that was simple. So why are we doing this? Let’s start with some simple browser security—something called the same origin policy. Same Origin Policy As the browser becomes more and more of an application platform, application de- velopers have compelling reasons read more..
Figure 9-23. Naming an S3 bucket in the S3 Management Console This is where CORS comes into the picture. CORS allows developers of remote data and content to designate which domains (through a whitelist) can interact with their content. Using Web Fonts in Your Application There are a number of ways to use a web font within your web pages, such as calling read more..
Figure 9-24. The html5hacks S3 bucket • Hosting the font in an Amazon S3 bucket works great, except with Firefox, which enforces the same origin policy on all resources. So the response from the remote server will be denied. • Converting the font to Base64 adds additional weight to the stylesheet, and does not take advantage of caching. An exploration into the read more..
Figure 9-25. An uploaded BebasNeue font Adding the Web Font to Your Web Page In order to add a web font to our page, we need to add a single stylesheet to an HTML page. Here is our page. Let’s call it index.html, and add a tag pointing to our base stylesheet, styles.css. In our styles.css let’s add the following and point to our uploaded file. read more..
Now we’ll open a browser and point to our newly created HTML page. In Opera (see Figure 9-26), Safari, and Chrome our header tag is being styled correctly. Figure 9-26. Opera browser showing the BebasNeue font But if we view it in Firefox, we are having issues (see Figure 9-27). If we examine the request for our font in the Chrome Dev Tools Network tab, read more..
Figure 9-27. Firefox browser failing to show the BebasNeue font What Is CORS? The CORS specification uses the object to send and receive head- ers from the originating web page to a server that is properly configured in order to enable cross-site requests. The server accepting the request must respond with the header with either a wildcard ( ) or the read more..
Figure 9-28. Firefox browser showing an empty response Configuring CORS at Amazon S3 You should already be at your Amazon Management Console. Click on Proper- ties Permissions Edit CORS configuration, and you should receive a modal prompt. The configuration can accept up to 100 rule definitions, but for our web font we will only need a few. For this example we will read more..
So, let’s add our new configuration to our Editor and save (see Figure 9-29). Figure 9-29. Configuring CORS in the S3 Management Console Now, let’s return to Firefox and reload the page. We should now see the header font styled with our BebasNeue web font, as shown in Figure 9-30. 413 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
HACK 76 Figure 9-30. Firefox browser successfully showing the BebasNeue font There is much more to learn about CORS, most notably, HTTP usage with certain MIME types, and sending cookies and HTTP authentication data with requests if so requested by the CORS-enabled server. So get out there and starting creating your own CORS hacks. Control an HTML5 Slide Deck with read more..
Robodeck is a culmination of HTML5 hacks, all wrapped up in one framework. It is a project hosted at GitHub, and demo’ed at Heroku (see Figure 9-31), that provides a starting point for building such presentations. This hack will walk through the creation of this framework. Figure 9-31. Robodeck demo hosted at Heroku This hack exposes you to both the server-side read more..
Let’s download Deck.js to a location on our computer (see Figure 9-32), and wait until we have a basic application built before we move these files to the appropriate directory. Figure 9-32. Deck.js home page Node.js and Express We will use Node.js as our simple web server to handle requests and responses from the browser, and the Express framework to read more..
Now you can list the files in your directory with the command: You should now have the files and directories necessary to build and run a simple Node.js/Express application. First, we need to include the necessary modules in our manifest file, package.json: You can see here that we have included a few modules to build this project. We have already introduced read more..
Figure 9-33. Initial Express application Establishing Routes We now have the beginnings of a basic Express web application. Let’s open the app.js file and take a look. We can see that our basic Express app is only accepting requests from one URL scheme, the root. This is why we get the basic response when we nav- igate to http://localhost:3000. In order to read more..
We will also need to accept s from our Sencha 2.0 mobile applica- tion: one from the URL http://localhost/next to advance the slide deck, and the other from the URL http://localhost/prev to slide the deck back. Hack #84 is dedicated to the concept of building routes in Node.js. So if you want the complete lowdown on how routes work, read that particular read more..
This is because two of our routes, and , will not need to return a response in the form of HTML markup. Those routes will, in turn, generate a web socket message that will be sent only to the clients that are listening. The clients that have connected at the root URL and received the desktop view will also receive a script tag with a Socket.IO script read more..
This markup provides three slides. Navigate to your browser and use the right-arrow key to advance the deck to the second slide. Figure 9-34 shows the second one that includes the title “HTML5 rocks.” Notice the hash tag on the URL: http://localhost: 3000/#remote matches the indicated in the second slide. We have also included a section that will be updated read more..
And finally, we will need to instantiate the Deck.js deck by calling: Now for the mobile route, we will need the mobile layout, which will contain the re- sources required to respond to requests from mobile devices. Remember, mobile de- vices should access the application from localhost:3000/x in order to receive the mobile-optimized application. In the mobile read more..
The mobile layout contains all of the Sencha 2.0 dependencies to create the HTML5 mobile web application. The smartphone view is injected within the mobile container and is intended to be for nontablet web clients. We could also have tablet-specific views, or we could use CSS3 media queries to respond to the different viewports by configuring our markup with read more..
Figure 9-35. Adding Deck.js to the public directory Polyfill WebSocket Support with Socket.IO Socket.IO aims to make real-time apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. For more on polyfills, refer to this book’s Preface or to Hack #55 . In order to provide real-time connectivity on every browser, read more..
Figure 9-36. Socket.IO home page Fortunately the Node.js community has made it extra simple to include Socket.IO within your application and to be up and running with a web socket server in no time. We already installed the module in the beginning of this hack, so now we will require it and begin to use the API. To get started we need to open our read more..
Now we’ll add the following (1511) declaration: Here, we begin to create our Socket.IO implementation on the server. Notice that we are passing the app object to the method of the Socket.IO application so that both will be listening on the same port. We then set up an event handler to handle the client connection event. Next, we push the unique read more..
You can test this functionality by opening a number of tabs within your browser, or even separate browser instances anywhere on your network that has access to local- host:3000 and access to the presentation at the root URL http://localhost:3000. Each instance will receive a web socket message and update all connected clients with the client total (see Figure read more..
Figure 9-39. Apple Safari requesting geolocation For more details and code snippets see Hack #59 . Setup for Mobile and Install of Sencha 2.0 Sencha Touch 2 is a high-performance HTML5 mobile application framework that enables developers to build fast and impressive apps that work on all mobile web browsers. For the purposes of this hack, we have chosen the framework read more..
Figure 9-40. Robodeck mobile built with Sencha 2.0 In the views section you saw that we included all the dependencies necessary to build a Sencha 2.0 application. In order for those links to access the correct files we need to download Sencha 2.0 and install the files in the /public directory. Our /public di- rectory will now look like Figure 9-41. 431 read more..
Figure 9-41. Adding Sencha 2.0 to the /public directory Now we will only need to update two files from within Sencha’s app directory to use Sencha’s declarative syntax for building applications. First we will open the app.js file located in the app/app directory and create a new . Now we’ll define the namespace in the property and use the method to read more..
Finally, in the app/app/views directory, we’ll open Home.js, where we will define our own custom function and call it from within the click handler of our two custom buttons, Forward and Back. 433 CHAPTER 9: HACKING HTML5 CONNECTIVITY www.it-ebooks.info read more..
And that’s really all we need to send s at the click of a button within our Sencha 2 mobile application. Finally, remember the routes we set up in the beginning of this hack to accept the requests to the URLs http://localhost:3000/next and http://localhost:3000/back? Now we can make use of them. Once the request is received, we trigger a web socket read more..
HACK 77 HACK 78 Inspect a Socket.IO Connection to Determine If It Is Native or Emulated Chrome Developer tools can help with debugging network traffic. You can also disable web sockets to demonstrate the power of Socket.IO polyfills. In this hack we’ll investigate the power of Socket.IO. Earlier, I explained that Socket.IO provides the ability to polyfill socket support for read more..
Figure 9-43. XHR-polling polyfill from Socket.IO node-spdy To serve up our simple SPDY implementation we will default to Node.js as we often have throughout this text. We will make use of Fedor Indutny’s node-spdy. You can pull down the hello_world example from GitHub. Let’s go ahead and the entire directory, and then navigate to the hello_world example: Now read more..
Let’s navigate to https://localhost:3232/, and we should see “Hello World” (see Figure 9-44). Be sure to include the “https://” in the URL, or your request will not be accepted. Figure 9-44. Simple “Hello World” from node-spdy We made a simple request, and the server responded with “Hello World.” You are not going to see a major improvement to your read more..
www.it-ebooks.info read more..
10 Pro HTML5 Application Hacks with Node.js Up to this point, this book has provided a sample collection of hacks that cover a large portion of the HTML5 feature suite. But what about building professional HTML5 ap- plications? As you can see in the latter chapters of the book, some of the HTML5 specifications are advancing the technologies at the connectivity layer. read more..
To get started, we only need to navigate to an empty directory within our filesystem and create an empty file, such as server.js. We’ll add the following to the file: Now we can execute the code with the file by running the following from the command line: Let’s walk through what is going on here. At the top of the file there is a method which read more..
In this hack, we are interested in understanding the very basics of HTTP and how Node.js helps us build web applications quickly and easily. We will begin by examining the HTTP and objects. To simplify, think of the request as an input and the response as an output. The server and the HTTP module will process the incoming request, and return a response read more..
443 CHAPTER 10: PRO HTML5 APPLICATION HACKS WITH NODE.JS www.it-ebooks.info read more..
444 HTML5 HACKS www.it-ebooks.info read more..
1 “The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.” (Wikipedia) A Little Background on HTTP1 When the Node.js HTTP server module accepts a request from a client such as your browser, it creates a new object to hold all the read more..
In this example, the property is set to . As I mentioned earlier, the creators of HTTP were forward-thinking enough to build in a way for the browser to request an upgrade to a different protocol. This is the handshake mechanism for WebSocket. If you would like to examine the object further, read the official API documentation of the object. And now, read more..
447 CHAPTER 10: PRO HTML5 APPLICATION HACKS WITH NODE.JS www.it-ebooks.info read more..
headers, the application can then query a lookup web service that contains detailed properties about the particular device. Properties such as screen size, camera access, and hardware acceleration, just to name a few, can then be used to build conditional logic around which assets and markup are returned to the client. It has long been considered a bad practice to read more..
HACK 81 We now have the basics of device detection. Obviously, this is a simplified example of a production-ready system. In a production system, the application would most likely pass the user agent string to another application that fronts a database, or to a third- party web service. The application or web service could then look up information, log errors, read more..
451 CHAPTER 10: PRO HTML5 APPLICATION HACKS WITH NODE.JS www.it-ebooks.info read more..
HACK 82 Use the Node Package Manager to Add a Web Application Framework As a Third- Party Module Adding modules to Node.js applications is simple with the Node Package Manager (NPM). Adding the Express web application framework to your application is as simple as adding it to your application manifest and installing it via NPM. First, we need to understand how read more..
HACK 83 Use the Express Application Generator to Bootstrap Your App Express’s application generator executable helps you build the skeleton for your ap- plication from the command line. Why Use Express? In earlier hacks we were operating on the and objects using only the HTTP module. Node.js ships with another “core” module called Connect that pr o- vides an additional layer read more..
Let’s take a closer look at the app.js file. This is what you get by default: 454 HTML5 HACKS www.it-ebooks.info read more..
HACK 84 But let’s break this down into the bare essentials to get running: Now we can install dependencies: and start the server: Build a Custom Module to Handle Routing Modularize the handling of requests made to your application within your own custom module. In our main app.js file, we will make a few changes. First, our generator already created a new module read more..
For the sake of demonstration, and in case you have the need to use static HTML files, we will disable the layout engine and configure Express to serve static HTML files from the /public directory. We will also turn off layout support. Here is the app.js file: The module contains the file index.js, which contains our routing logic: And here is a basic read more..
HACK 85 Now, we have created our first module and we are using routes to serve markup to the browser. As your application grows, you will need to continue to modularize its func- tionality so that your app.js file does not become difficult to maintain. Configure Express to Use a View Engine Configuring Express to render views with a view read more..
HACK 86 The module containing the file index.js still contains the same routing logic: But now we have an index.jade file containing the markup in a less verbose, simpler syntax: In the next few hacks, we will take a closer look at Jade and her sister language, Stylus. Use Jade Layouts to DRY Up Your Application’s Views DRY (Don’t Repeat Yourself) is a read more..
There are other similar metalanguages, such as HAML, Less, and Sass, of which you may already be familiar. These tools are somewhat different, but the concepts are the same. Before we jump into our hacks, we will need to get somewhat acquainted with the Jade syntax. You had a taste of the simplified syntax in the previous hacks, but if you would like to get read more..
Now, the markup returned from the view will be injected into the body of the document via the body call. Here is the index.jade file: Now view your application at http://localhost:3000, and you will see your two files, layout.jade and index.jade, aggregated together and output to the browser (see Figure 10-1). Figure 10-1. Initial simple view 460 HTML5 HACKS read more..
HACK 87 Layout is turned on by default, but if you ever have the need, such as in Hack #84 , you can turn it off with the following configuration: Use a Jade Partial to Create a Common Navigation Bar in Your Views Now you can reuse content within your views through the use of partials. To demonstrate this capability, let’s inject some shared content, such as read more..
Our browser should now look like Figure 10-2. Figure 10-2. Navigation partial As we navigate through the application by clicking the links within our navigation bar, we will see that we are now sharing the layout and the navigation partial with each example page. This hack is a very simple demonstration of how to keep our assets organized, as you might imagine read more..
HACK 88 Before we depart from our exploration of Jade, let’s finish up with one more hack that will demonstrate the power of our new template engine. Use Jade Mixins to Populate Your Views with Data Jade mixins are another tool in your toolkit that you can utilize in your views to reduce code bloat. You can use mixins to help iterate through data from a read more..
Now, we should have access to the data in our view via the object. In order to iterate through this data and display it in our view, Jade provides some very helpful features. One of those is mixins. Wikipedia defines a mixin as “A class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for read more..
Figure 10-3. Basic list Now we can add more logic to our example3.jade file. We can also nest a mixin within another mixin. 465 CHAPTER 10: PRO HTML5 APPLICATION HACKS WITH NODE.JS www.it-ebooks.info read more..
HACK 89 Through the power of the Jade metalanguage and some of its robust features, we are able to create clear and concise markup to manage our views (see Figure 10-4). Set Up Expressive, Dynamic, Robust CSS with Stylus Stylus makes CSS for your Express application easier to write and maintain. As mentioned earlier, Stylus is a dynamic metalanguage that read more..
Figure 10-4. Topping and yogurt lists First, let’s add the Stylus module to our current application. In this hack we will simply include Stylus and compile a .styl file to .css. 467 CHAPTER 10: PRO HTML5 APPLICATION HACKS WITH NODE.JS www.it-ebooks.info read more..
Here is a new style.styl stylesheet, where we will leverage our new syntax: If we switch back to our style.css, we will notice that our stylesheet is being compiled at runtime: We now have an app up and running on Node.js with Express, Jade, and Stylus working together to render output to the web browser (see Figure 10-5). 468 HTML5 HACKS www.it-ebooks.info read more..
470 HTML5 HACKS www.it-ebooks.info read more..
For the sake of this hack, I have removed some of the less significant code and com- ments as they are out of scope. An entire book could be written about the issues and considerations being addressed within this template. We will focus on the items that are most related to HTML5; this will certainly be enough to get you started. Open index.html in read more..
Conditional-stylesheets Conditional-stylesheets were developed to overcome CSS rendering bugs in a number of highly adopted browsers. Since not all browsers correctly implement the CSS specifications released by the W3C, writing cross-browser CSS can be complex. The Conditional-stylesheets approach helps to ensure that your site renders consistently across as many popular browsers read more..
Integrating with the Node.js/Express Application Unfortunately, this only provides a benefit for hacking on HTML5 features that are not dependent on communication with an HTTP or WebSocket Server. In order to have a fully capable application that can be deployed to a remote server, we need to integrate this boilerplate into our basic web application that we built in read more..
As you can see, having our markup, styles, and script declarations in .jade files makes managing this template a less complex endeavor. 474 HTML5 HACKS www.it-ebooks.info read more..
Become an HTML5 Hacker The title of this chapter is “Pro HTML5 Application Hacks with Node.js” because at this point you should be ready to build production-deployable applications that use many of the HTML5 specifications you learned in the other chapters of this book. The intent was to celebrate and share in the hacker tradition by presenting you with step-by-step read more..
www.it-ebooks.info read more..
We’d like to hear your suggestions for improving our indexes. Send email to email@example.com. Index A accelerometers, 82 Access-Control-Allow-Origin, 411 accessible websites dropzone attribute, 219 subtitles, 139, 147 Adobe Photoshop color palette, 76 fonts, 66 alpha transparency, 73–76 Amazon S3 bucket, 404 animateMotion tag, 199–201 animation in donation thermometer, 376 read more..
high-res media, 177–181 image data, 176 image fill, 171–176 shapes, 158–164 transparency, 170 canvas.mozGetAsFile ( ), 244 canvas.toBlob ( ), 244 captions, 156 card flips, 113–117 CDN (Content Delivery Network), 120, 405 Chrome Developer Tools, 355, 410 FileSystem Explorer plug-in, 262 Frame, 471 cloud drive, hosting a web font on, 404 CloudFront, 405 code bloat, reducing, 463 read more..
data transfer object, 217–219 data URIs, 87–92, 244, 245, 407 data URLs, 239, 243, 245 date input type, 24 date pickers, 265 Deck.js, 415 Dependency Module Management Sys- tem, 441 design mode, 230 device adaptation, 123 device orientation, 81–85 device-specific response, 450 display canvas, 137 div tags, problems with, 3, 7 Django, 243 doctype tag, 1, 471 document.createElement, 8 read more..
elimination of, 19 how it works, 17 real-time, 38 server- vs. client-side, 16 validation criteria, 18 formnovalidate attribute, 19 FullCalendar.js, 264 G generic font families, 56 Geocoding API, 280 geofence, 291–297 geolocation broadcast movement, 298–301 geofence, 291–297 how it works, 273 longitude and latitude, 274–279 moving location pin, 286–291 polyfills for, 302–304 read more..
multimedia, 125–156 audio-rich applications, 150 MediaElement.js, 154 native functionality, 125, 128 subtitles, 139, 147 video APIs, 130 video backgrounds, 135 video codecs, 128 video cues, 143 video embedding, 125 N navigation bars, 461 Node Package Manager (NPM), 361, 452 node-spdy, 435 Node.js application generator, 453 as simple web server, 416 detect user agent string, 448 device-specific read more..
request objects, 442, 448 requestAnimationFrame method, 182– 188 required attribute, 11, 18, 245 resource name, 445 respond.js, 117–120 response objects, 442, 450 responsive design media queries, 77, 117 object detection, 449 responsive video, 155 retina-display-ready media canvas tag, 177–181 reverse-geocode locations, 280–284 RGBA colors, 74, 76, 165 Robodeck desktop and mobile views, read more..
T talking_about_count property, 310 TCP socket communication, 384 text effects, 70–73 text flow control, 70 text shadow property, 72 Thin, 394 third-party libraries, 343 third-party modules, 452 3D transforms, 107 timers and web workers, 325 element creation, 328 element initialization, 328 real-world uses, 338 worker library, 334 tooltip elements, 375 Tornado, 394 toString method, 249 read more..
Wejrowski, Brett, 254 window.history methods, 236 WOFF (web-only font format), 61 word-wrap attribute, 71 writeHead ( ) method, 450 ws Module, 360 WYSIWYG editor, 229–232 X XHR-polling polyfills, 435 XHR2, 244 Y YepNope.js, 252, 302 YUI date picker, 24 YUI slider utility, 29 Z zebra stripe data tables, 86 ZIP files, 260 zip.js library, 260 485 INDEX www.it-ebooks.info read more..
About the Authors Jesse Cravens is a senior engineer at frog, where he works with the world’s leading companies, helping them to design, engineer, and bring to market meaningful prod- ucts and services. He possesses a deep background in web application development and has recently been focusing on single-page web application architecture, the mo- bile web, and HTML5. read more..
Write Your Review