41
Looking through the folders, you’ll see that they contain CSS, JavaScript, and HTML files as well as
favicon.ico, crossdomain.xml for Flash and Silverlight, a 404.html page, robots.txt for search engines,
and QUnit testing functionality.
CSS Support
Two CSS files are included out of the box: the main CSS file used by the site, named style.css, and a
starter script for hand-held devices, named handheld.css. The style.css file includes several different
tips, tricks, and best practices that can be used to handle rendering HTML across multiple browsers
(including IE6). It adds in some clever features, such as hiding content from a page and ensuring the
content doesn’t take up any space while still making it available to screen readers. Figure 4 shows an
example of a CSS class named visuallyhidden that performs the screen reader trick.
Figure 4: Screen reader trick employed by HTML5 Boilerplate
/* Hide only visually, but have it available for screenreaders: by Jon Neal.
www.webaim.org/techniques/css/invisiblecontent/ & j.mp/visuallyhidden */
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px;
overflow: hidden; padding: 0; position: absolute; width: 1px; }
/* Extends the .visuallyhidden class to allow the element to be focusable when
navigated to via the keyboard: drupal.org/node/897638 */
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow:
visible; position: static; width: auto; }
The style.css file also includes the popular clearfix solution that can be used to prevent margins from
collapsing on child elements when the children are floated. If you’ve ever written HTML and CSS
where you floated children left or right, then had to add a final child with “clear:both” in the style
to make things look right, you’ll find that this fix greatly simplifies the process since you can simply
apply the clearfix class, as the code in Figure 5 shows.
Figure 5: The “clearfix” used to handle floating children in HTML pages
/* The Magnificent Clearfix: Updated to prevent margin-collapsing on child ele-
ments. j.mp/bestclearfix */
.clearfix:before, .clearfix:after { content: “\0020”; display:
block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }
/* Fix clearfix: blueprintcss.lighthouseapp.com/projects/15318/tickets/5-extra-
margin-padding-bottom-of-page */
.clearfix { zoom: 1; }
Print styles are also included to simplify the process of removing backgrounds, handling links, printing
table rows, handling images, and more, as shown in Figure 6.
Figure 6: Using HTML5 Boilerplate’s support for printing pages
/**
* Print styles.
76
Chapter 8: Getting Started Using HTML5 Boilerplate
43
*
* Inlined to avoid required HTTP connection: www.phpied.com/delay-loading-your-
print-css/
*/
@media print {
* { background: transparent !important; color: black !important; text-
shadow: none !important; filter:none !important;
-ms-filter: none !important; }
/* Black prints faster: sanbeiji.com/archives/953 */
a, a:visited { color: #444 !important; text-decoration: underline; }
a[href]:after { content: “ (“ attr(href) “)”; }
abbr[title]:after { content: “ (“ attr(title) “)”; }
.ir a:after, a[href^=”javascript:”]:after, a[href^=”#”]:after {
content: “”; }
/* Don’t show links for images, or javascript/internal links */
pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
thead { display: table-header-group; }
/* css-discuss.incutio.com/wiki/Printing_Tables */
tr, img { page-break-inside: avoid; }
@page { margin: 0.5cm; }
p, h2, h3 { orphans: 3; widows: 3; }
h2, h3{ page-break-after: avoid; }
}
Moving into the js folder in the project, you’ll find jQuery, IE6 .png support, and Modernizer scripts
included in the js/libs folder. Custom scripts can go in the scripts.js file, and plug-in scripts can go
in plugins.js. Any custom libraries used in the site can go in the mylibs folder. Keep in mind that the
folders are only a recommended folder structure, and as the HTML5 Boilerplate site likes to say, all
the code is “delete-key friendly,” so feel free to reorganize things to fit your needs.
The index.html File
When you open the index.html file provided by HTML5 Boilerplate, you’ll find some interesting code
right at the top, as shown next:
<!doctype html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7 ]> <html class=”no-js ie6” lang=”en”> <![endif]-->
<!--[if IE 7 ]> <html class=”no-js ie7” lang=”en”> <![endif]-->
<!--[if IE 8 ]> <html class=”no-js ie8” lang=”en”> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html class=”no-js” lang=”en”>
<!--<![endif]-->
First, you’ll note that the standard HTML5 doctype declaration is defined. I can’t tell you how happy
it makes me to have this simple definition since the different XHTML doctype options were hard to
remember. Immediately under the doctype you’ll notice the inclusion of several conditional state-
Chapter 8: Getting Started Using HTML5 Boilerplate
77
22
ments to check for IE6, IE7, IE8, and IE9 along with other modern browsers. By default this code adds
a no-js CSS class name and the appropriate IE class on the root <html> element if Internet Explorer is
hitting the site. If another browser such as Chrome or Firefox is hitting the page, then only the no-js
class is added to the <html> element. The no-js class is used to handle browsers that don’t support
JavaScript. For example, if you wanted to hide all <h1> elements in the page when a browser doesn’t
support JavaScript, you could add the following definition into style.css:
.no-js h1 { display: none; } /* Hide h1 tags if Javascript is disabled */
At this point, you may wonder how the no-js class gets removed from the <html> element when a
browser does support JavaScript. After all, if the browser supports JavaScript, it wouldn’t make much
sense to have a no-js class defined. To handle this situation, the HTML5 Boilerplate code adds a refer-
ence to the Modernizr script within the head section of index.html:
<script src=”js/libs/modernizr-1.7.min.js”></script>
By default, Modernizr will locate the <html> element and change no-js to js if JavaScript is supported
by the browser. Figures 7 and 8 show an example of how Modernizr modifies the <html> element;
the example in Figure 7 uses the IE9 developer tools (press F12 when viewing a site in IE9 to get to
the developer tools), and the Figure 8 example uses the Chrome developer tools (Ctrl+Shift+I).
Figure 7: Viewing the <html> element using the IE9 developer tools
Figure 8: Viewing the <html> element using the Chrome developer tools
HTML5 Boilerplate’s index.html page includes several other interesting features, such as the meta tags
shown in Figure 9.
78
Chapter 8: Getting Started Using HTML5 Boilerplate
38
Figure 9: Meta tags added by HTML5 Boilerplate that handle encoding and rendering functionality
<meta charset=”utf-8”>
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame.
Remove this if you use the .htaccess -->
<meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1”>
The first meta tag sets the character set to utf-8 and is a shorthand version of what was used previ-
ously in web pages:
<meta http-equiv=”Content-Type” content=”text/html;charset=utf-8” >
At first glance, setting the character set may seem trivial and unimportant, but it can actually stop
some script attacks that rely on utf-7, so it’s recommended that you define it in your pages. The
second meta tag shown in Figure 9 is used to force Internet Explorer to use its most modern rendering
engine. This comes into play with IE8 and IE9 since they have compatibility modes that a user can
select in the address bar and ensures that Internet Explorer compatibility mode rendering isn’t used
(even if the user selected it). Although this second meta tag doesn’t pass the latest W3C validation test,
it’s good to have to prevent IE8/IE9 browsers from reverting back to IE7 mode due to the user enabling
compatibility mode.
Moving down further in the <head> element within index.html, you’ll see that Google’s Content
Delivery Network (CDN) is used to load jQuery:
<script
src=”//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js”></script>
This provides several benefits related to caching and location. A user visiting a site that references the
Google CDN URL for jQuery will have the script cached in their browser. If they then visit your site
that references the same CDN script file, the cached version will be used, resulting in faster page load
times. Also, Google’s CDN servers (note that Microsoft also provides a CDN for jQuery) are located
throughout the world, so when the jQuery script gets loaded for the first time, a server close to the
user’s location will normally be hit.
Having a reference to the CDN version of jQuery is nice, but it’s always good to have a fallback in
case the CDN is inaccessible for any reason. HTML5 Boilerplate uses a trick I like to use as well to
embed a local copy of jQuery if the CDN version can’t be loaded. It does so by checking for the exis-
tence of the window.jQuery object. If the object isn’t found, then the CDN script wasn’t loaded suc-
cessfully and a local version of the script is loaded instead:
<script>window.jQuery || document.write(“<script src=’js/libs/jquery-1.5.1.min.
js’>\x3C/script>”)</script>
Another key item added into index.html is a reference to the Google Analytics script for tracking page
hits and other details. If you have a Google Analytics account, you can update your site’s ID in the
provided script:
Chapter 8: Getting Started Using HTML5 Boilerplate
79
40
<script>
var _gaq=[[“_setAccount”,”UA-XXXXX-X”],[“_trackPageview”]];
(function(d,t){var g=d.createElement(t),
s=d.getElementsByTagName(t)[0];g.async=1;
g.src=(“https:”==location.protocol?”//ssl”:”//www”)+
“.google-analytics.com/ga.js”;
s.parentNode.insertBefore(g,s)}(document,”script”));
</script>
Testing Features
In addition to the HTML, CSS, and JavaScript features added by HTML5 Boilerplate, support for
QUnit is also included out of the box. QUnit is a JavaScript test library used to test the Query project
code but can also be used to test JavaScript code that you write. Within the project created by HTML5
Boilerplate, you’ll find a folder named test that contains the qunit.js and associated CSS file as well as
a sample test HTML page and test script. The test script provides a few basic examples of using QUnit
to perform assertions and test logging functionality available in the plugins.js file included with the
project (see Figure 10). A complete discussion of QUnit is outside the scope of this article, but you
can read more about it on the jQuery QUnit page.
Figure 10: QUnit test script provided by HTML5 Boilerplate
module(“example tests”);
test(“HTML5 Boilerplate is sweet”,function(){
expect(1);
equals(“boilerplate”.replace(“boilerplate”,”sweet”),”sweet”,
“Yes. HTML5 Boilerplate is, in fact, sweet”);
})
// these test things from plugins.js
test(“Environment is good”,function(){
expect(3);
ok( !!window.log, “log function present”);
var history = log.history && log.history.length || 0;
log(“logging from the test suite.”)
equals( log.history.length - history, 1, “log history keeps track” )
ok( !!window.Modernizr, “Modernizr global is present”)
})
HTML5 Jump-Start
Whether you’re an experienced web developer or someone looking to get into HTML5 web
development, the code generated by the HTML5 Boilerplate site can help jump-start your proj-
ects and also serve as a good learning environment. HTML5 Boilerplate includes several tips
and tricks to handle cross-browser issues that crop up, implements proven best practices, and
80
Chapter 8: Getting Started Using HTML5 Boilerplate
How to C#: Basic SDK Concept of XDoc.PDF for .NET Document Protect. You may add PDF document protection functionality into your C# program. OutLines. This class describes bookmarks in a PDF document.
add bookmark pdf; copy bookmarks from one pdf to another
6
ultimately simplifies the process of writing HTML5-compliant web pages. Although the code
generated by HTML5 Boilerplate only provides skeleton HTML/CSS/JS code, you can visit other
sites such as initializr.com that build on the skeleton code while supplying functional pages with
graphics and placeholders.
Chapter 8: Getting Started Using HTML5 Boilerplate
81
29
Chapter 9: Start Using HTML5
in Your Web Apps—Today!
You can include HTML5 features in your web apps -- even if they run
on older browsers
By Wallace McClure
Download the code:
http://www.devproconnections.com/content/content/141812/141812_HTML5_DesktopLaptop_code.
zip
HTML5 is the direction for web-based applications. All you have to do is listen to the material from
any technical conference or keep an eye on web developer online community discussions to know
that HTML5 is important. Each day, I read about new and exciting HTML5 features and uses for those
features -- witness the many new features in the latest versions of Internet Explorer (IE), Chrome, and
Firefox.
Mobile application development is definitely where HTML5 has gotten its start, but HTML5 is not lim-
ited to mobile. Here, I will build on the information in Chapter 6 along with many other great articles
on HTML5 published in DevProConnections and delve into some of the HTML5 features that are
available today and that you can use immediately to provide solutions for your customers now. In this
article, we’ll see what can be done in ASP.NET running in a modern web browser, such as Chrome,
Firefox, Safari, and the recently released IE10. (As an FYI, in December 2011 Chrome 15 was named
the most popular web browser version by StatCounter, though Internet Explorer is the most popular
browser family.)
Drag and Drop to Upload Files
Who isn’t familiar with the concept of dragging an object from one place in a computer UI and drop-
ping it somewhere else on screen, resulting in an action occurring? This capability has been around
for a long time in Windows, Mac, and other operating systems. Although this fact isn’t widely known,
browser support for drag and drop is available for web apps. You may have seen this in Google+.
Going further, there is also the ability to upload files via a drag-and-drop visual interface. I have found
82
Chapter 9: Start Using HTML5 in Your Web Apps—Today!
39
that drag and drop for file uploading works in the most recent versions of Chrome, Firefox, and IE10.
Unfortunately, this means that IE9 and earlier don’t support the necessary APIs for file upload.
The first step in building a drag-and-drop file-upload capability into your web application is to
assemble the necessary libraries. We’ll use the following libraries:
• Modernizr: a library that allows a program to test the browser for capabilities
• jQuery: We’ll use jQuery for its ability to modify the document object model (DOM) in browsers.
The first step in creating the file-upload capability is to create a couple of divs that will be used for
our file upload. Figure 1 shows the HTML that accomplishes this. In this example, we have two divs.
The dropArea div will be used to accept drops. The oldUpload div will be used for browsers that
don’t support the necessary APIs to allow for the user to upload files via drag and drop.
Figure 1: Creating divs for the file upload
<div id=”dropArea” class=”dZone”>
</div>
<div id=”oldUpload” class=”dZone”>
Upload files:<br />
<input type=”file” id=”fileUp” name=”fileUp” /><br />
<input type=”submit” id=”fileSubmit” name=”fileSubmit” value=”Upload” />
</div>
The next step is to determine whether the browser supports the necessary drag-and-drop APIs along
with the browser-based file-reading APIs. This is done by using the following code:
var supported = ((Modernizr.draganddrop) &&
(typeof (window.FileReader) != “undefined”));
This code uses the Modernizr library to determine whether the browser supports the necessary drag-
and-drop interface. If the browser in use supports drag and drop, the value true is returned. The next
step is to check the browser for file-reader support. Once we have determined whether the browser
supports drag and drop and file-reading APIs, our code will then really get going.
Figure 2 shows the sample code for determining whether the application should display the drag-and-
drop file user interface or the old-style upload interface.
Figure 2: Determining the file-upload interface style
dz = $(“#dropArea”);
dropZone = dz[0];
dz.removeClass(“error”);
isdnds = IsDragAndDropFileUploadSupported();
old = $(“#oldUpload”);
if (isdnds) {
dz.text(startUpText);
old.hide();
Chapter 9: Start Using HTML5 in Your Web Apps—Today!
83
31
}
else {
dz.hide();
}
In this code, we need to get references to the dropArea div and the oldUpload div area. If the browser
supports drag and drop as well as the FileReader APIs, the oldUpload div area is hidden. If the
browser does not support drag and drop and the FileReader APIs, the dropArea div is hidden. Figure 3
shows how the upload interface will appear, depending on browser type.
Figure 3: File-upload interface for older and newer browsers
Drag and Drop
HMTL5’s drag and drop is a powerful API for enabling users to copy, move, and delete items with
just a few mouse clicks. Drag and drop provides a set of events that a developer’s JavaScript code can
monitor and respond to. These events are set up:
• drag: an event that is fired during the drag operation
• dragend: an event that is fired when a drag operation is finished; this event typically occurs when
the mouse button is released or the Esc key is pressed
• dragenter: an event that occurs when the mouse is moved over an element while a drag is currently
underway
• dragleave: occurs when the mouse is moved over an element while a drag is currently underway
• dragover: occurs when the mouse is moved over an element while a drag is currently underway
• dragstart: an event that is fired when a user begins dragging an object
• drop: an event that occurs when the dragged elements are dropped/released onto an element that
accepts data
Your next question might be, What types of elements can accept drag/drop events? Elements that can
accept these drag-and-drop events include editable controls and content areas, such as the <div/> tag.
Figure 4: Setting up drag-and-drop events
// Alter text and add a drag effect
dropZone.ondragover = function () {
if (isdnds) {
84
Chapter 9: Start Using HTML5 in Your Web Apps—Today!
48
dz.addClass(“hover”);
dz.text(“Drop files here to watch the processing start.”);
}
return false;
};
// Update the text
dropZone.ondragleave = function () {
if (isdnds) {
dz.text(“Drop files here to begin processing.”);
}
}
// Remove the drag effect when stopping our drag
dropZone.ondragend = function () {
if (isdnds) {
dz.removeClass(“hover”);
dz.text(startUpText);
old.show();
}
return false;
};
// The drop event handles file upload.
dropZone.ondrop = function (event) {
// Stop the browser from opening the file in the window
event.preventDefault();
if (isdnds) {
dz.removeClass(“hover”);
// Get the file and the file reader
iFiles = event.dataTransfer.files.length;
files = event.dataTransfer.files;
var i = 0;
var strOut = “”;
for (i = 0; i < iFiles; i++) {
// Validate file size
if (files[i].size > @MaxFileSize) {
strOut += “File name:” + files[i].name +
“ is too large to upload. File size:” + files[i].size + “. “;
}
}
if (strOut != “”) {
dz.text(strOut);
dz.addClass(“error”);
return false;
}
fileUploadMethod(0);
}
};
Chapter 9: Start Using HTML5 in Your Web Apps—Today!
85
Documents you may be interested
Documents you may be interested