jQuery Primer in Html5

jQuery Primer in Html5

Writing JavaScript that works well across all major web browsers in a clean and concise way is a difficult chore. There are many libraries that make this process less painful, and jQuery is one of the most popular. It’s easy to use, has a wide array of existing libraries, and is a good fit for easily creating fallback solutions. This appendix introduces you to the parts of the jQuery library that we use elsewhere in the book. It’s not meant to be a replacement for jQuery’s excellent documentation, 1 nor is it going to be an exhaustive list of the features and methods available. It will, however, give you a good place to start jQuery Primer in Html5.

Loading  jQuery Primer in Html5

You can grab the jQuery library from the jQuery website 2 and link to the jQuery script directly, but we’ll load jQuery from Google’s servers, like this jQuery Primer in Html5:

<script type= "text/javascript"
charset="utf-8"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" >
</script>

Browsers can make only a few connections to a server at a time. If we distribute our images and scripts to multiple servers, our users can download our pages faster. Using Google’s content delivery network has an additional benefit as well—since other sites link to the jQuery library at Google, our visitors may already have the library cached by their browser. As you probably already know, browsers use the full URL to a file to decide whether it has a cached copy. If you plan to work with jQuery on a laptop or on a computer without constant Internet access, you will want to link to a local copy instead jQuery Primer in Html5.
jQuery Basics jQuery Primer in Html5
Once you have loaded the jQuery library on your page, you can start working with elements. jQuery has a function called the jQuery( ) function. This one function is the heart of the jQuery library. We use this function to fetch elements using CSS selectors and wrap them in jQuery objects so we can manipulate them. There’s a shorter version of the jQuery( ) function, $();, and that’s what we use in this book. Throughout the rest of this appendix, I’ll refer to this function as “the jQuery function.” Here’s how it works: If you wanted to find the h1 tag on a page, you’d use the following jQuery Primer in Html5:

$("h1" );
$(".important" );

Take a look at that again. The only difference between those two examples is the CSS selector we used. The jQuery function returns a jQuery object, which is a special JavaScript object containing an array of the DOM elements that match the selector. This object has many useful predefined methods we can use to manipulate the elements we selected. Let’s take a look at a few of those in detail. Methods to Modify Content We use several jQuery methods to modify our HTML content as we work through this book.
Hide and Show to jQuery Primer in Html5
The hide( ) and show( ) methods make it easy to hide and show user interface elements. W e can hide one or many elements on a page like this jQuery Primer in Html5:

$("h1" ).hide();

To show them, we simply call the show( ) method instead. We use the hide( ) method throughout this book to hide page sections that only need to appear when JavaScript is disabled, such as transcripts or other fallback content. html, val, and attr We use the html( )method to get and set the inner content of the specified element. Here, we’re setting the content between the opening and closing h1 tags to “Hello World. ” The v al ( ) method sets and retrieves the value from a form field. for jQuery Primer in Html5 It works exactly like the html( ) method. The attr( ) method lets us retrieve and set attributes on elements. append, prepend, and wrap The append( ) method adds a new child element after the existing elements. Given we have a simple form and an empty unordered list, like this:

<form id= "add" >
<label for= "task" >Task</label>
<input type= "text" id="task" >
<input type= "submit" value="Add" >
</form>
<ul id= "links" >
</ul>

we can create new elements in the list by appending these new elements when we submit the form jQuery Primer in Html5.

$(function(){
$("#add" ).submit(function(event){
event.preventDefault();
var new_element = $( "<li>" + $( "#email" ).val() + "</li>" );
$("#links" ).append(new_element);
});
});

The prepend() method works the same way as the append() method but inserts the new element before any of the existing ones. The wrap() method wraps the selected element with the element represented by the jQuery object you specify jQuery Primer in Html5.

$("h1" ).css( { "color" : "red" ,
"text-decoration" : "underline" }
);
var wrapper = $( "#message" ).wrap("<div><h2>Message</h2></div>" ).parent();

We can define these one at a time, but we can also use a JavaScript hash to assign many CSS rules to the element: However, it’s not a good idea to mix style with scripts. We can use jQuery’s addClass( ) and removeClass( ) methods to add and remove classes when certain events occur. W e can then associate styles with these classes. We can change the background on our form fields when they receive and lose focus by combining jQuery events and classes.

$("input" ).focus(function(event){
$(this).addClass("focused" );
});
$("input" ).blur(function(event){
$(this).removeClass("focused" );
});

Events to jQuery Primer in Html5
We often need to fire events when users interact with our page, and jQuery makes this very easy. In jQuery, many common events are simply methods on the jQuery object that take a function. For example, we can make all the links on a page with the class of popup open in a new window like this jQuery Primer in Html5:

var links = $( "#links a" );
 links.click(function(event){
 var address = $( this).attr('href' );
 event.preventDefault();
 window.open(address);
 });

Inside our jQuery event handler, we can access the element we’re working with by using the this keyword. On line 3, we pass this to the jQuery function so we can call the attr( ) method on it to quickly retrieve the link’s destination address. We use the preventDefault( ) function to keep the original event from firing so it doesn’t interfere with what we’re doing. Bind Some events aren’t directly supported by jQuery, and we can use the bind( ) method to handle them. For example, when implementing the Drag and Drop part of the HTML5 specification, we need to cancel out the ondragover event. W e use the bind( ) like this jQuery Primer in Html5

target = $( "#droparea" )
target.bind('dragover' , function(event) {
if (event.preventDefault) event.preventDefault();
return false;
});

The Original Event on jQuery Primer in Html5

When we use any of the jQuery event functions like bind( ) or click( ), jQuery wraps the JavaScript event in its own object and copies only some of the properties across. Sometimes we need to get to the actual event so we can access those properties that didn’t get cloned. jQuery events give us access to the original event with the appropriately named originalEvent property. W e can access the data property of the onmessage event like this jQuery Primer in Html5:

$(window).bind("message" ,function(event){
var message_data = event.originalEvent.data;
});

Document Ready in jQuery Primer in Html5
The phrase “unobtrusive JavaScript” refers to JavaScript that’s kept completely separate from the content. Instead of adding onclick attribute butes to our HTML elements, we use event handlers like we just talked about in Section B.5, Events,We unobtrusively add behavior to our document, without modifying the document itself. Our HTML is not dependent on our users having JavaScript enabled. One drawback to this method is that JavaScript can’t “see” any of the elements in our document until they’ve been declared. We could include our JavaScript code in a script block at the bottom of the page after everything else has been rendered, but that isn’t reusable across pages. W e could wrap our code in JavaScript’s window.onLoad() event handler, but that event gets fired after all the content has loaded. This could cause a delay, meaning your users could be interacting with things before your events have been attached. W e need a way to add our events when the DOM is loaded but before it’s been displayed. jQuery’s document.ready function does exactly this, in a way that works across browsers. We use it like this jQuery Primer in Html5:

$(document).ready(function() {
alert("Hi! L am a popup that displays when the page loads" );
});

There’s a shorter, more compact version that we’ll be using throughout our code, which looks like this:

$(function() {
alert("Hi! L am a popup that displays when the page loads" );
});

We use this pattern in almost every example in this book so that we can easily, unobtrusively add fallback solutions to our projects. This is only a small sampling of what we can do with jQuery. Aside from the document manipulation features, jQuery provides methods for serializing forms and making Ajax requests and includes some utility functions that make looping and DOM traversal much easier. Once you become more comfortable with its use, you’ll no doubt find many more ways to use it in your projects to jQuery Primer in Html5.

Where to Go Next in Html5

Where to Go Next in Html5

Most of this book focuses on Most of this book focuses on things you can do right now, but there are some other things you will be able to start using very soon things you can do right now, but there are some other things you will be able to start using very soon that will make standards-based web development even more interesting, from 3D canvas support with W e b G L to new storage APIs, CSS3 transitions, and native drag-and-drop support. This chapter discusses some of the things on the horizon, so you can get an idea of what to expect. W e ’ ll talk about things that you may be able to use in at least one browser but don’t have good enough fallback solutions or are too far undefined to start working with right now: Where to Go Next in Html5.

CSS3 Transitons for Where to Go Next in Html5

Interaction invitations are important to good user experience design, and CSS has supported the :hover pseudoclass for some time so that we can do some basic interaction cues on our elements. Here’s some CSS markup that styles a link so it looks like a button

a.button{
padding: 10px;
border: 1px solid #000;
text-decoration: none;
}
a.button:hover{
background-color: #bbb;
color: #fff
}

When we place our cursor over the button, the background changes from white to gray, and the text changes from black to white. It’s an instant transition. CSS3 transitions 3 let us do quite a bit more, including simple animations that were possible only with JavaScript. For example, we can make this transition into a cross-fade by adding the following highlighted code to the style definition Where to Go Next in Html5:

a.button{
padding: 10px;
border: 1px solid #000;
text-decoration: none;
webkit-transition-property: background-color, color;
webkit-transition-duration: 1s;
webkit-transition-timing-function: ease-out;
a.button:hover{
background-color: #bbb;
color: #fff
}

On line 5 Where to Go Next in Html5, we specify what properties get the transition applied. In this case, we’re changing the background and foreground colors. We specify the duration of the animation on line 6, and we specify the transition’s timing function on line 7. Timing Functions The transition-timing-function property describes how transitions happen  over time in relation to the duration you’ve set. W e specify this timing function using a cubic Bezier curve, which is defined by four control points on a graph. Each point has an X value and a Y value, from 0 to 1. The first and last control points are always set to (0.0,0.0) and (1.0,1.0), and the two middle points determine the shape of the curve. A linear curve has its control points set to the two end points, which creates a straight line at a 45-degree angle. The four points for a linear curve are ( (0.0, 0.0), (0.0,0.0), (1.0, 1.0), (1.0, 1.0) ), and it looks like this Where to Go Next in Html5:

Where to Go Next PHP and ASP

Where to Go Next

A more complex curve, with points ( (0.0, 0.0), (0.42,0.0), (1.0, 1.0), (1.0, 1.0) ), called an ease-in curve, looks like this for Where to Go Next in Html5:

Where to Go Next PHP and ASP

Where to Go Next

This time, only the second point has changed, which is what causes the bottom-left part of the line to curve. Even more complex is the ease-in-out curve, which has a curve at the bottom and at the top, like this Where to Go Next in Html5:

Where to Go Next PHP and ASP

Where to Go Next

The points for this curve are ( (0.0, 0.0), (0.42,0.0), (0.58, 1.0), (1.0, 1.0) ).

We can specify these points right in the CSS property, or we can use some predefined ones like we did in our example. Our choices are default, ease-in, ease-out, ease-in-out, ease-out-in, and cubic-bezier, in which you set the points of the curve yourself. If you want the rate to be constant, you’d use linear. If you want the animation to start slow and speed up Where to Go Next in Html5, you’d use ease-in. If you want to learn a little more about making these curves, there’s a great public domain script 4 that shows you examples and helps you see the coordinates. Play around with transitions, but keep in mind that you want your interface to be usable first and pretty second. Don’t build transitions that frustrate the user, such as things that flicker or take too long to animate. You may also want to investigate CSS3 animations, 5 another method for changing CSS properties over time Where to Go Next in Html5.

Web Workers for Where to Go Next in Html5

Web Workers 6 are not part of the HTML5 specification, but you may find them useful if you need to do some background processing on the client side, so they’re worth mentioning. We use JavaScript for all of our client-side coding, but JavaScript is a single-threaded language—only one thing can happen at a time. If a task takes a long time, we force the user to wait until the task has finished. Web Workers solve this problem by creating a simple way to write concurrent programs. If we have a script called workesj.r that does some image processing, we can invoke it like this to Where to Go Next in Html5:

var worker = new Worker( "worker.js" );

Any JavaScript file can be launched as a worker, but in order for the worker to be independent, your worker script can’t access the DOM. That means you can’t manipulate elements directly. Our main script can send messages to the worker script using for Where to Go Next in Html5.

$("#button" ).click(function(event){
$("#output" ).html("starting..." );
worker.postMessage("start" );
});

Native Drag-and-Drop Support  for Where to Go Next in Html5

Letting users drag and drop interface elements is something we’ve been able to do with JavaScript libraries for quite a while, but the W3C has adopted Microsoft’s Drag and Drop implementation as part of the HTML5 specification. 7 It’s supported by Firefox, Safari, Internet Explorer, and Chrome, but in actuality it’s a mess with Where to Go Next in Html5. The implementation at first appears to be straightforward; we designate an element as “draggable,” we then designate an element that watches for a dropped object, and we execute some code when that happens. In reality, it’s not nearly that simple. To demonstrate, let’s create a simple drag-and-drop interface that lets us drag small images into a drop area that will load the larger version.

<div id="images">
<img src= "images/red_thumb.jpg"
data-large="images/red.jpg" alt="A red flower" >
<img src= "images/purple_thumb.jpg"
data-large="images/purple.jpg" alt="A white and purple flower" >
<img src= "images/white_thumb.jpg"
data-large="images/white.jpg" alt="A white flower" >
</div>
<div id="preview">
<p>Drop images here </p>
</div>

We are using custom data attributes heret o hold the source oft he larger version of our photos  to Where to Go Next in Html5.

Where to Go Next in Html5 PHP and ASP

Where to Go Next in Html5

Most of this book focuses on things you can do right now, but there are some other things you will be able to start using very soon

Next we’ll add some basic styles to float the two columns to Where to Go Next in Html5:

#images img{
-webkit-user-drag
}
#images{
float: left;
width: 240px;
margin-right: 10px;
}
#preview{
float: left;
width: 500px;
background-color: #ddd;
height: 335px;
}
.hover{
border: 10px solid #000;
background-color: #bbb !important;
}

At this point,Now let’s add some events so we can drag the photos.
Drag-and-Drop Events to Where to Go Next in Html5
We’ll need to work with several events related to dragging and dropping elements.

Event                      Description
ondragstart                Fires when the user starts dragging the object
ondragend                  Fires when the user stops dragging the object for any
                           reason
ondragenter                Fires when a draggable element is moved into a drop
                           listener
ondragover                 Fires when the user drags an element over a drop
                           listener
ondreagleave               Fires when the user drags an element out of drop
                           listener
ondrop                     Fires when the user drops an element into a drop
                           listener successfully
ondrag                     Fires when the user drags an element anywhere; fires
                           constantly but can give X and Y coordinates of the
                           mouse cursor

To Make Where to Go Next in Html5 That’s a total of seven events just to handle dragging and dropping elements, and some of the events have default behaviors. If we don’t override them, the whole thing fails. First, we need to define all of our list items as draggable.

var contacts = $('#images img');
contacts.attr('draggable', 'true');

We are adding the draggable HTML5 attribute. We could do this in our markup, but since we require JavaScript to do the interaction, we’ll apply this attribute with our script. When we drag the image, we want to grab the address of the large image and store it. We’ll bind to the ondragstart event, and to keep it simple and cross-platform, we’ll use jQuery’s bind( ) method Where to Go Next in Html5.

contacts.bind('dragstart', function(event) {
var data = event.originalEvent.dataTransfer;
var src = $(this).attr( "data-large" );
data.setData("Text" , src);
return true;
});

The specification provides a dataStorage mechanism that lets us specify the type of data and the data itself, which is passed along as part of the event. jQuery’s bind( ) method wraps the event in its own object, so we use the originalevent property on 2 to access the real event. W e store the URL to the image on the event by using the setData( ) method, using Text as the data type. Now that we can drag elements, let’s talk about how we fire events when the user drops the elements. Dropping Elements for Where to Go Next in Html5
We want our “To” form field to act as our drop target, so we’ll locate it and bind the drop event Where to Go Next in Html5.

var target = $('#preview');

target.bind('drop', function(event) {
var data = event.originalEvent.dataTransfer;
var src = ( data.getData('Text') );

var img = $( "<img></img>" ).attr("src" , src);
$(this).html(img);
if (event.preventDefault) event.preventDefault();
return(false);
});

We retrieve the image address we passed with the event using the get-Data( ) method on line 5, and we then create a new image element that we push into our content region. We need to cancel the default ondrop event so it won’t fire when our user drops the element onto the target. To do that, we need to use both preventdefault( ) and return false. Internet Explorer needs return false, and other browsers need preventDefault( ). If we try to use this in Chrome or Safari right now, it won’t work quite right. At a minimum, we have to override the ondragover element. If we don’t, our ondrag event won’t respond. So, we’ll do that by using this code Where to Go Next in Html5:

target.bind('dragover', function(event) {
if (event.preventDefault) event.preventDefault();
return false;
});

File Dragging
Moving text and elements around the page is just the beginning. The specification allows developers to create interfaces that can receive files from the user’s computer. Uploading a photo or attaching a file is as easy as dragging the file onto a specified target. In fact, Google’s Gmail supports this if you are using Firefox 3.6 or Chrome 5. If you want to explore this further, take a look at the excellent article 9 by Leslie Michael Orchard.
All Is Not Well to Where to Go Next in Html5
The behavior in various browsers is, to be kind, inconsistent. IE 8 works, but it breaks if we try to set the data type for setData( ) to Url instead of Text. Additionally, in order to support dragging of elements that are not images or links in Safari 4, we’d need to add additional CSS to our style sheet.

#contents li{
-webkit-user-drag
}

Throughout this book, we’ve discussed how important it is to keep style and behavior separated from content, and this flies right in the face of that concept.Don’t try dragging text onto form fields. Modern browsers already let you do this, but there’s no good way to override that behavior. As it stands, we can get much better results with much less code by using a JavaScript library that supports dragging and dropping like jQuery UI. 10 Even with a library, we still have one last thing to worry about: accessibility. The specification doesn’t say anything about how to handle users who can’t use a mouse. If we implemented drag-and-drop functionality on our interfaces, we’d need to develop a secondary method that didn’t require JavaScript or a mouse to work, and that method would depend on what we’re trying to do. This specification has a lot of potential, but it also has some things that need to be addressed. Use it if it makes sense, but ensure you don’t force your users into something they can’t use to Where to Go Next in Html5.

Web GL for Where to Go Next in Html5
We talked about the canvas element’s 2D context in this book, but there’s another specification in progress that describes how to work with 3D objects. The Web G L 11 specification isn’t part of HTML5, but Apple, Google, Opera, and Mozilla are part of the working group and have implemented some support in their browsers. Working with 3D graphics is well beyond the scope of this book, but the site Learning Web GL 12 has some great examples and tutorials. Indexed Database API to Where to Go Next in Html5
In this book, we talked about two methods for storing data on the client: Web Storage and W e b SQL Storage. The Mozilla foundation took issue with the W e b SQL specification, stating that they didn’t think it was a good idea to base the specification on a specific SQL engine. They introduced a new specification called the Indexed Database API, which is scheduled to become a standard of its own. 13 The Indexed Database API is a key/value store similar to the Web Storage APIs like localStorage and sessionStorage, but it provides methods for performing advanced queries. Unfortunately, at the time of writing, there are no implementations of this specification available, so it’s not even worth going into any implementation details because they will most likely change between now and the time it’s implemented. Firefox 4 and Chrome 7 are expected to include support. This is the specification you’ll want to watch closely, because Web SQL is at an impasse, and Mozilla has stated numerous times that it has no plans to ever implement W e b SQL in Firefox, because Mozilla is uncomfortable with the SQL dialect and doesn’t think that the specification should be based on one particular database implementation. The Web SQL specification uses the SQLite database dialect, which could change independent of the specification. It’s very likely that Internet Explorer will implement this specification as well, because Microsoft has taken an interest in its development.

Where to Go .Next PHP and ASP

Where to Go .Next

Client-Side FormV ali dati on to Where to Go Next in Html5
The HTML5 specification lists several attributes we can use to validate user input on the client side, so we can catch simple input errors before the user sends the requests to the server. We’ve been able to do this for years using JavaScript, but HTML5 forms can use new attributes to specify the behavior. W e can ensure that a user has required a form field by adding the required attribute like this:

<label for="name">Name </label>
<input type="text" name="name" autofocus required id="name">

Browsers can then prevent the form from submitting and display a nice error message, and we don’t have to write a single line of JavaScript validation. Opera does this right now, as you can see. This lets users fail early, without waiting for a server response to find out whether they made a mistake Where to Go Next in Html5. This behavior could be disabled or unavailable or just simply not correctly implemented, so you still need to make sure you have a server-side strategy for validating data. It’s definitely something to start thinking about now, though, because you can then easily locate the required fields and style the interface with CSS so that the required fields stand out from the rest for Where to Go Next in Html5. You can take this one step further witht he pattern attribute, which lets you specify a regular expression to ensure that the content meets your criteria.

<label for="name">Name </label>
<input type="text" name="name" autofocus required id="name">

Although Where to Go Next in Html5 no current browser uses this through the user interface, using this markup as the basis for a JavaScript validation library would be easy to implement.  Onward! It’s an exciting time to be a developer. This book just barely scrapes the surface of what the future holds for web developers. There’s so much more to the specifications, and I encourage you to dig deeper. I hope you take the things you learned here and continue to build and explore, watching the various specifications as you do so. Now go build something awesome to Where to Go Next in Html5!

Finding Yourself: From Geolocation

Finding Yourself: From Geolocation

Geolocation is a technique for discovering where people are, based on their computer’s location. Of course, “computer” really can mean smart phone, tablet, or other portable device as well as a desktop computer. Geolocation determines a person’s whereabouts by looking at their computer’s IP address, MAC address, Wi-Fi hotspot location, or even GPS coordinates if available. Although not strictly part of HTML5 the specification, Geolocation is often associated with HTML5 because it’s coming on the scene at the same time. Unlike W e b Storage, Geolocation was never part of the HTML5 specification. Like W e b Storage, it’s a very useful technology that is already implemented in Firefox, Safari, and Chrome. Let’s see how we can use it.

Locating Awesomeness for Finding Yourself: From Geolocation

We have been asked to create a contact page for the AwesomeCo website, and the CIO has asked whether we could show people’s location on a map along with the various AwesomeCo support centers. He’d love to see a prototype, so we’ll get one up and running quickly. We’ll use Google’s Static Map API for this because it doesn’t require an API key and we’re just going to generate a very simple map. AwesomeCo service centers are located in Portland, Oregon; Chicago, Illinois; and Providence, Rhode Island. Google’s Static Map API makes it really easy to plot these points on a map. All we have to do is construct an img tag and pass the addresses in the URL, like this to Finding Yourself: From Geolocation:

<img id= "map" alt="Map of AwesomeCo Service Center locations"
src="https://maps.google.com/maps/api/staticmap?
&amp;size=900x300
&amp;sensor=false
&amp;maptype=roadmap
&amp;markers=color:green|label:A|1+Davol+square,+Providence,+RI+02906-3810
&amp;markers=color:green|label:B|22+Southwest+3rd+Avenue,Portland,+OR
&amp;markers=color:green|label:C|77+West+Wacker+Drive+Chicago+IL">

We define the size of the image, and then we tell the Maps API that we did not use any sensor device, such as a GPS or client-side geolocation with the information we’re passing to this map. Then we define each marker on the map by giving it a label and the address. We could use a comma-separated pair of coordinates for these markers if we had them, but this is easier for our demonstration.
How to Be Found to Finding Yourself: From Geolocation. We need to plot our visitor’s current location on this map, and we’ll do that by providing another marker on the map by using our latitude and longitude for a new marker. W e can ask the browser to grab our visitor’s latitude and longitude, like this:

navigator.geolocation.getCurrentPosition(function(position) {
showLocation(position.coords.latitude, position.coords.longitude);
});

This method prompts the user to provide us with their coordinates. If the visitor allows us to use their location information, we call the showLocation( ) method. The showLocation( ) method takes the latitude and longitude and reconstructs the image, replacing the existing image source with the new one. Here’s how we implement that method for Finding Yourself: From Geolocation:

 var showLocation = function(lat, lng){
 var fragment = "&markers=color:red|color:red|label:Y|" + lat + "," + lng;
 var image = $( "#map" );
 var source = image.attr( "src" ) + fragment;
 source = source.replace( "sensor=false" , "sensor=true" );
 image.attr("src" , source);
 };

Rather than duplicate the entire image source code, we’ll append our location’s latitude and longitude to the existing image’s source. Before we assign the modified image source back to the document, we need to change the sensor parameter from false to true. We’ll do that on line 5 with the replace( ) method. When we bring it up in our browser, we’ll see our location, marked with a “Y” among the other locations. To see an example, take a look next page to Finding Yourself: From Geolocation.

Finding Yourself: Geolocation PHP and ASP

Finding Yourself: From Geolocation

Geolocation is a technique for discovering where people are, based on their computer’s location. Of course, “computer” really can

Falling Back to Finding Yourself: From Geolocation

As it stands, visitors to the page will still see the map with the locations of the AwesomeCo support centers, but we will get a JavaScript error if we try to load our page. W e need to detect support for geolocation before we attempt to get the visitor’s location, like this to Finding Yourself: From Geolocation:

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
showLocation(position.coords.latitude, position.coords.longitude);
});
}else{
};

Google’s Ajax API 11 does location lookup, so it’s a great fallback solution. You will need to obtain an API key to use this on your site when you go live, but you don’t need one to try this locally.
Our fallback looks like this here to Finding Yourself: From Geolocation:

var key = "your_key" ;
 var script = "http://www.google.com/jsapi?key=" + key;
 $.getScript(script, function(){
 if ((typeof google == 'object') &&
 google.loader && google.loader.ClientLocation) {
 showLocation(google.loader.ClientLocation.latitude,
 google.loader.ClientLocation.longitude);
 }else{
 var message = $( "<p>Couldn't find your address.</p>" );
 message.insertAfter("#map" );
 };
 });

We’re using jQuery’s getScript( ) method to load the Google Ajax API. We then use Google’s ClientLocation( ) method on line 5 to get a visitor’s location and invoke our showLocation( ) method to plot the location on our map. Unfortunately, Google can’t geolocate every IP address out there, so we may still not be able to plot the user on our map; therefore, we account for that by placing a message underneath our image. Our fallback solution isn’t foolproof, but it does give us a greater chance of locating our visitor.
Without a reliable method of getting coordinates from the client, we’ll just need to provide a way for the user to provide us with an address, but that’s an exercise I’ll leave up to you.
The Future to Finding Yourself: From Geolocation
The techniques we talked about in this chapter, although not all part of HTML5 proper, represent the future of web development. We’ll be pushing many more things to the client side. Better history management will make Ajax and client-side applications much more intuitive. Web Sockets can replace periodic polling of remote services for the display of real-time data. Cross-document Messaging lets us merge web applications that usually would never be able to interact, and Geolocation will eventually let us build better location-aware web applications, which Finding Yourself: From Geolocation, become more and more relevant every day with the growing mobile computing market. Explore these APIs and keep an eye on their adoption. You may soon find these to be invaluable tools in your web development toolbox for Finding Yourself: From Geolocation.

Chatting with Web Sockets

About Chatting with Web Sockets

Real-time interaction has been something web developers have been trying to do for many years, but most of the implementations have involved using JavaScript to periodically hit the remote server to check for changes. HTTP is a stateless protocol, so a web browser makes a connection to a server, gets a response, and disconnects. Doing any for Chatting with Web Sockets

kind of real-time work over a stateless protocol can be quite rough. The HTML5 specification introduced Web Sockets, which let the browser make a stateful connection to a remote server. We can use W e b Sockets to build all kinds of great applications. One of the best ways to get a feel for how W e b Sockets work is to write a chat client, which, coincidentally, AwesomeCo wants for its support site. AwesomeCo wants to create a simple web-based chat interface on its support site that will let members of the support staff communicate internally, because the support staff is located in different cities. We’ll use W e b Sockets to implement the web interface for the chat server. Users can connect and send a message to the server. Every connected user will see the message. Our visitors can assign themselves a nickname by sending a message such as “/nick brian,” mimicking the IRC chat protocol. W e won’t be writing the actual server for this, because that has thankfully already been written by another developer to Chatting with Web Sockets.

The Chat Interface for Chatting with Web Sockets

We are looking to build a very simple chat interface on the next with a form to change the user’s nickname, a large area where the messages will appear, and, finally, a form to post a message to the chat. In a new HTML5 page, we’ll add the markup for the chat interface, which consists of two forms and a div that will contain the chat messages to Chatting with Web Sockets.

Chatting with Web Sockets PHP and ASP

Chatting with Web Sockets

<div id="chat_wrapper">
<h2>AwesomeCo Help!</h2>
<form id="nick_form" action="#" method="post" accept-charset="utf-8">
<p>
<label>Nickname
<input id="nickname" type="text" value="GuestUser"/>
</label>
<input type="submit" value="Change">
</p>
</form>
<div id="chat">connecting....</div>
<form id="chat_form" action="#" method="post" accept-charset="utf-8">
<p>
<label>Message
<input id="message" type="text" />
</label>
<input type="submit" value="Send">
</p>
</form>
</div>

We’ll also need to add links to a style sheet and a JavaScript file that will contain our code to communicate with our Web Sockets server for Chatting with Web Sockets.

<script src='chat.js' type='text/javascript'></script>
<link rel="stylesheet" href="style.css" media="screen">

Our style sheet contains these style definitions:

chat_wrapper{
width: 320px;
height: 440px;
background-color: #ddd;
padding: 10px;
}
#chat_wrapper h2{
margin: 0;
}

#chat{
width: 300px;
height: 300px;
overflow: auto;
background-color: #fff;
padding: 10px;
}

we set the overflow property on the chat message area so that its height is fixed and any text that doesn’t fit should be hidden, viewable with scrollbars. With our interface in place, we can get to work on the JavaScript that will make it talk with our chat server. Talking to the Server No matter what Web Sockets server we’re working with, we’ll use the same pattern over and over. We’ll make a connection to the server, and then we’ll listen for events from the server and respond appropriately to Chatting with Web Sockets.

Event         Description
onopen()     Fires when the connection with the server has been
              established
on message()  Fires when the connection with the server sends a
              message  
onclose()    Fires when the connection with the server has been
              lost or closed

In our chat.js file, we first need to connect to our Web Sockets server, like this for Chatting with Web Sockets:

var webSocket = new WebSocket('ws://localhost:9394/');

When the browser opens the connection to the server, we put a message in the chat window. Next, we need to display the messages sent to the chat server. We do that by defining the onmessage() method like this:

webSocket.onmessage = function(event){
$('#chat').append("<br>" + event.data);
$('#chat').animate({scrollTop: $('#chat').height()});
};

The message comes back to us via the event object’s data property for Chatting with Web Sockets. We just add it to our chat window. W e ’ l prepend a break so each response falls on its own line, but you could mark this up any way you wanted. Next we’ll handle disconnections. The onclose( ) method fires whenever the connection is closed.

webSocket.onclose = function(event){
$("#chat" ).append('<br>Connection closed');
};

Now we just need to hook up the text area for the chat form so we can send our messages to the chat server here for Chatting with Web Sockets .

$(function(){
$("form#chat_form" ).submit(function(e){
e.preventDefault();
var textfield = $( "#message" );
webSocket.send(textfield.val());
textfield.val("" );
});
}

We hook into the form submit event for Chatting with Web Sockets, grab the value of the form field, and send it to the chat server using the send() method. We implement the nickname-changing feature the same way, except we prefix the message we’re sending with “/nick.” The chat server will see that and change the user’s name.

$("form#nick_form" ).submit(function(e){
e.preventDefault();
var textfield = $( "#nickname" );
webSocket.send("/nick " + textfield.val());
});

That’s all there is to it. Safari 5 and Chrome 5 users can immediately participate in real-time chats using this client. Of course, we still need to support browsers without native Web Sockets support. We’ll do that using Flash.

Falling Back with Chatting with Web Sockets

Browsers may not all have support for making socket connections, but Adobe Flash has had it for quite some time. We can use Flash to act as our socket communication layer, and thanks to the web-socket-js library, implementing a Flash fallback is a piece of cake. We can download a copy of the plug-in 10 and place it within our project. We then need to include the three JavaScript files on our page to Chatting with Web Sockets:

<script type="text/javascript" src="websocket_js/swfobject.js"></script>
<script type="text/javascript" src="websocket_js/FABridge.js"></script>
<script type="text/javascript" src="websocket_js/web_socket.js"></script>
<script src='chat.js' type='text/javascript'></script>
<link rel="stylesheet" href="style.css" media="screen">
</head>
<body>
<div id="chat_wrapper">
<h2>AwesomeCo Help!</h2>
<form id="nick_form" action="#" method="post" accept-charset="utf-8">
<p>
<label>Nickname
<input id="nickname" type="text" value="GuestUser"/>
</label>
<input type="submit" value="Change">
</p>
</form>
<div id="chat">connecting....</div>
<form id="chat_form" action="#" method="post" accept-charset="utf-8">
<p>
<label>Message
<input id="message" type="text" />
</label>
<input type="submit" value="Send">
</p>
</form>
</div>
</body>
</html>

With that inp lace, our chat application will worko n allm ajor browsers, provided that the server hosting your chat server also serves a Flash Socket Policy file. Flash Socket Policyi What? For security purposes, Flash Player will only communicate via sockets with servers that allow connections to Flash Player. Flash Player attempts to retrieve a Flash Socket Policy file first on port 843 and then on the same port your server uses. It will expect the server to return a response like this:

<cross-domain-policy>
<allow-access-from domain=" *" to-ports=" *" />
</cross-domain-policy>

This is a very generic policy file that allows everyone to connect to this service to Chatting with Web Sockets. You’d want to specify the policy to be more restrictive if you were working with more sensitive data. Just remember that you have to serve this file from the same server that’s serving your Web Sockets server, on either the same port or the port  The example code for this section contains a simple Flash Socket Policy server written in Ruby that you can use for testing.Servers, for more on how to set that up on your own environment for testing.
Chat servers are just the beginning. with Web Sockets, we now have a robust and simple way to push data to our visitors’ browsers.

Chatting with Web Sockets

The book’s source code distribution contains a version of the Web Sockets for Chatting with Web Sockets server we’re targeting. It’s written in Ruby, so you’ll need a Ruby interpreter. For instructions on getting Ruby working on your system, see the file RUBY_README.txt within the book’s source code files. You can start it up by navigating to its containing folder and typing this:

ruby server.rb

In addition to the chat server, there are two other servers you may want to use while testing the examples in this chapter for server, client.rb, serves the chat interface . The first server, client.rb, serves the chat interface and JavaScript files. The other server, flashpolicyserver, serves a Flash Policy file that our Flash-based Web Sockets fallback code will need to contact in order to connect to the actual chat server. Flash Player uses these policy files to determine whether it is allowed to talk to a remote domain. If you’re running on a Mac or a Linux-based operating system, you can start all these servers at once with this to Chatting with Web Sockets.

Taking Across Domains in Html5

About Taking Across Domains

Client-side web applications have always been restricted from talking directly to scripts on other domains, a restriction designed to protect users. There are numerous clever ways around this restriction, including the use of server-side proxies and clever URL hacks. But now there’s a better way. The HTML5 specification introduced Cross-document Messaging , an API that makes it possible for scripts hosted on different domains to pass messages back and forth. For example, we can have a form on http:// support.awesomecompany.com post content to another window or iframe for Taking Across Domains.

whose content is hosted on http://www.awesomecompany.com. It turns out that for our current project, we need to do just that. AwesomeCo’s new support site will have a contact form, and the support manager wants to list all the support contacts and their email addresses next to the contact form. The support contacts will eventually come from a content management system on another server, so we can embed the contact list alongside the form using an iframe. The catch is that the support manager would love it if we could let users click a name from the contact list and have the email automatically added to our form. We can do this quite easily, but you’ll need to use web servers to properly test everything on your own setup. The examples we’re working on here don’t work in every browser unless we use a server. See the sidebar on the following page for more on this. The Contact List We’ll create the contact list first for Taking Across Domains.

Our basic markup will look like this for Taking Across Domains:

<ul id="contacts">
<li>
<h2>Sales</h2>
<p class="name">James Norris</p>
<p class="email">[email protected] </p>
</li>
<li>
<h2>Operations</h2>
<p class="name">Tony Raymond</p>
<p class="email">[email protected]</p>
</li>
<li>
<h2>Accounts Payable</h2>
<p class="name">Clark Greenwood</p>
<p class="email">[email protected] </p>
</li>
<li>
<h2>Accounts Receivable</h2>
<p class="name">Herbert Whitmore</p>
<p class="email">[email protected]</p>
</li>
</ul>

On that page, we’ll also load both the jQuery library and our own custom application.js file and a simple style sheet. We’ll place this in our head section here to Taking Across Domains:

<script type= "text/javascript"
charset="utf-8"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" >
</script>
<script type= "text/javascript"
src="javascripts/application.js" >
</script>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">

The style sheet for the contact list looks like this Taking Across Domains:

ul{
list-style: none;
}
ul h2, ul p{margin: 0;}
ul li{margin-bottom: 20px;}

It’s just a couple of small tweaks to make the list look a little cleaner.When a user clicks an entry in our contact list, we’ll grab the email from the list item and post a message back to the parent window. The postMessage( ) method takes two parameters: the message itself and the target window’s origin. Here’s how the entire event handler looks for Taking Across Domains:

$(function(){
$("#contacts li" ).click(function(event){
var email = ($(this).find( ".email" ).html());
var origin = "http://192.168.1.244:3000/index.html" ;
window.parent.postMessage(email, origin);
});
});

You will need to change the origin if you’re following a long, since it has to match the URL of the parent window. 6 , Now we need to implement the page that will hold this frame and receive its messages. The Support Site The support site’s structure is going to look very similar, but to keep things separate, we should work in a different folder, especially since this site will need to be placed on a different web server to Taking Across Domains.

The Support Site for Taking Across Domains

The support site’s structure is going to look very similar, but to keep things separate, we should work in a different folder, especially since this site will need to be placed on a different web server. We’ll need to make sure you include links to a style sheet, jQuery, and a new. Our support page needs a contact form and an iframe that points to our contact list. We’ll do something like this:

<div id="form">
<form id="supportform">
<fieldset>
<ol>
<li>
<label for="to">To </label>
<input type="email" name="to" id="to">
</li>
<li>
<label for="from">From </label>
<input type="text" name="from" id="from">
</li>
<li>
<label for="message">Message</label>
<textarea name="message" id="message"></textarea>
</li>
</ol>
<input type="submit" value="Send!">
</fieldset>
</form>
</div>
<div id="contacts">
<iframe src="https://192.168.1.244:4567/index.html"></iframe>
</div>

We’ll style it up with this CSS that we add to style.css for Creating Taking Across Domains:

#form{
width: 400px;
float: left;
}
#contacts{
width: 200px;
float: left;
}
#contacts iframe{
border: none;
height: 400px;
}fieldset{
width: 400px;
border: none;
}
fieldset legend{
background-color: #ddd;
padding: 0 64px 0 2px;
}
fieldset>ol{
list-style: none;
padding: 0;
margin: 2px;
}
fieldset>ol>li{
margin: 0 0 9px 0;
padding: 0;
}
/* Make inputs go to their own line */
fieldset input, fieldset textarea{
display:block;
width: 380px;
}
fieldset input[type=submit]{
width: 390px;
}
fieldset textarea{
height: 100px;
}

This places the form and the iframe side by side and modifies the form. on the previous page Taking Across Domains. Receiving the Messages The on message event fires whenever the current window receives a message. The message comes back as a property of the event. We’ll register this event using jQuery’s bind( ) method so it works the same in all browsers.

$(function(){
$(window).bind("message" ,function(event){
$("#to" ).val(event.originalEvent.data);
});
});

jQuery’s bind( ) method wraps the event and doesn’t expose every property. W e can get what we need by accessing it through the event’s originalEvent property instead. If you open this in Firefox, Chrome, Safari, or Internet Explorer 8, you’ll see that it works extremely well. Now let’s make it work for IE 6 and 7.

Falling Back for Taking Across Domains

To support IE 6 and 7, we’ll use the jQuery Postback plug-in, which emulates cross-domain messaging. W e ’ l use jQuery’s getScript( ) method to pull that library in only when we need it. To do that, we’ll just detect whether the postMessage( ) method exists. First, we’ll modify our contact list for Taking Across Domains.

if(window.postMessage){
window.parent.postMessage(email, origin);
}else{
$.getScript("javascripts/jquery.postmessage.js" , function(){
$.postMessage(email, origin, window.parent);
});
}

Now, let’s turn our attention to the support site. We’ll use the same approach here, pulling in the library and calling the newly added receiveMessage() method Taking Across Domains.

if(window.postMessage){
$(window).bind("message" ,function(event){
$("#to" ).val(event.originalEvent.data);
});
}else{
$.getScript("javascripts/jquery.postmessage.js" , function(){
$.receiveMessage(
function(event){
$("#to" ).val(event.data);
});
});
}

That’s it! We can now talk across windows in a whole bunch of browsers. This is just the beginning, though; you can expand this technique to do two-way communication, too. Any window can be a sender or a receiver, so take a look at the specification and see what you can build to Taking Across Domains!

Storing Data in a Client-Side Relational Database in Html5

About Storing Data in Html5

The localStorage and sessionStorage methods give us an easy way to store simple name/value pairs on the client’s computer, but sometimes we need more than that The localStorage and sessionStorage methods give us an easy way to store simple name/value pairs on the client’s computer, but sometimes we need more than that. . The HTML5 specification initially introduced the ability to store data in relational databases to Storing Data in Html5. It’s since been spun off into a separate specification called Web SQL Storage. 6 If you have even a basic background in writing SQL statements, you’ll feel right at home in no time. To get you comfortable, we’ll use W e b SQL Storage to create, retrieve, update, and destroy notes in a client-side database. CRUD inY our Browser The term CRUD, an acronym for “Create, Retrieve, Update, and Delete,” 7 pretty much describes what we can do with our client-side database. The specification and implementations allow us to insert, select, update, and delete records. AwesomeCo wants to equip their sales team with a simple application to collect notes while they’re on the road. This application will need to let users create new notes, as well as update and delete existing ones . To change existing notes, we’ll need to let users retrieve them from the database. Here are the SQL statements we’ll need to write in order to make this to Storing Data in Html5.

Type                Statement
Create a note       INSERT INTO notes (title, note) V A L UES(" T est", "This is a note");
Retrieve            all
notes               SELECT id, title, note FROM notes;

Retrieve a specific     SELECT id, title, note FROM notes where id = 1;
note

Update a note              UPDATE notes set title = “bar”, note = “Changed” where id =1;
Delete a note                 DELETE FROM notes where id = 1;

<body>
<section id="sidebar">
<input type="button" id="new_button" value="New note">
<ul id="notes">
</ul>
</section>
<section id="main">
<form>
<ol>
<li>
<input type="submit" id="save_button" value="Save">
<input type="submit" id="delete_button" value="Delete">
</li>
<li>
<label for="title">Title </label>
<input type="text" id="title">
</li>
<li>
<label for="note">Note </label>
<textarea id="note"></textarea>
</li>
</ol>
</form>
</section>
</body>
</html>

This style sheet turns off the bullet points, sizes the text areas, and lays things out in two columns. Now that we have the interface done, we can build the JavaScript we need to make this work. Connecting to the Database We need to make a connection and create a database to Storing Data in Html5:

// Database reference
var db = null ;
// Creates a connection to the local database
connectToDB = function()
{
db = window.openDatabase( 'awesome_notes' , '1.0' ,
'AwesomeNotes Database' , 1024 *1024*3);
};

We are declaring the db variable at the top of ours cript. Doingt his makes it available to the rest of the methods we’ll create. 8 W e then declare the method to connect to the database by using the window.openDatabase method. This takes the name of the database, a version number, a description, and a size parameter. Creating the NotesT all be Our notes table needs three columns for Storing Data in Html5:
Field          Description
id                Uniquely identifies the note. Primary key, integer,
auto-         incrementing.
title           The title of the note, for easy reference.
Note          The note itself.

createNotesTable = function()
{
db.transaction(function(tx){
tx.executeSql(
"CREATE TABLE notes (id INTEGER \
PRIMARY KEY, title TEXT, note TEXT)", [],
function(){ alert( 'Notes database created successfully!' ); },
function(tx, error){ alert(error.message); } );
});
};

We fire the SQL statement inside a transaction for Storing Data in Html5, and the transaction has two callback methods: one for a successful execution and one for a failure. This is the pattern we’ll use for each of our actions to Storing Data in Html5. Note that the executeSql() method also takes an array as its second parameter. This array is for binding placeholders in the SQL to variables. This lets us avoid string concatenation and is similar to prepared statements in other languages. In this case, the array is empty because we have no placeholders in our query to populate. Now that we have our first table, we can make this application actually do something. Loading Notes When the application loads, we want to connect to the database, create the table if it doesn’t already exist, and then fetch any existing notes from the database here to Storing Data in Html5 .

// loads all records from the notes table of the database;
fetchNotes = function(){
db.transaction(function(tx) {
tx.executeSql('SELECT id, title, note FROM notes' , [],
function(SQLTransaction, data){
for (var i = 0; i < data.rows.length; ++i) {
var row = data.rows.item(i);
var id = row[ 'id' ];
var title = row[ 'title' ];
addToNotesList(id, title);
}
});
});
};

We are embedding the ID of the record into a custom data attribute. We will use that ID to locate the record to load when the user clicks the list item. W e then add the new list item we create to the unordered list in our interface with the ID of notes. Now we need to add code to load that item into the form when we select a note from this list to Storing Data in Html5.

Fetchnig a Specific Record with Storing Data in Html5

We could add a click event to each list item, but a more practical approach is to watch any clicks on the unordered list and then determine which one was clicked. This way, when we add new entries to the list (like when we add a new note), we don’t have to add the click event to the list.
With in our jQuery function, we’ll add this code for Storing Data in Html5:

$("#notes" ).click(function(event){
if ($(event.target).is( 'li' )) {
var element = $(event.target);
loadNote(element.attr("data-id" ));
}
});
loadNote = function(id){
db.transaction(function(tx) {
tx.executeSql('SELECT id, title, note FROM notes where id = ?' , [id],
function(SQLTransaction, data){
var row = data.rows.item(0);
var title = $( "#title" );
var note = $( "#note" );
title.val(row["title" ]);
title.attr("data-id" , row[ "id" ]);
note.val(row["note" ]);
$("#delete_button" ).show();
});
});
}

Falling Back with Storing Data in Html5

Unlike our other solutions, there are no good libraries available that would let us implement SQL storage ourselves, so we have no way to provide support to Internet Explorer users natively. However, if this type of application is something you think could be useful, you could convince your users to use Google Chrome, which works on all platforms, for this specific application. That’s not an unheard of practice, especially if using an alternative browser allows you to build an internal application that could be made to work on mobile devices as well. Another alternative is to use the Google Chrome Frame plug-in. This snippet gets read by the Google Chrome Frame plug-in and activates it for this page. If you want to detect the presence of the plug-in and prompt your users to install it if it doesn’t exist, you can add this snippet right above the closing body tag for Storing Data in Html5:

<script type= "text/javascript"
src=
"http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js" >
</script>
<script>
window.attachEvent("onload" , function() {
CFInstall.check({
mode: "inline" , // the default
node: "prompt"
});
});
</script>

This will give the user an option to install the plug-in so they can work with your site. Google Chrome Frame may not be a viable solution for a web application meant to be used by the general public, but it works well for internal applications like the one we just wrote. There may be corporate IT policies that prohibit something like this, but I’ll leave that up to you to work out how you can get something like this approved if you’re in that situation. Installing a plug-in is certainly more cost-effective than writing your own SQL database system to Storing Data in Html5.