Tag: JavaScript

HTML5 Series - Location

Being able to get a users location opens up some great functionality especially when used on mobile devices that could be anywhere. HTML5 makes it really easy to capture the users latitude and longitude in just a couple of lines of JavaScript.

What's important to remember though is the user always has the option of denying your request for their location so error handling is very important.

First you need to check to see if the device actually support geolocation by doing navigator.geolocation

1if (navigator.geolocation) {
2 // success code to go here
3} else {
4 alert("location not supported");
5}

Next we need to call navigator.geolocation.getCurrentPosition to get the current location. As capturing a location isn't something that happens instantly (first the browser will check with the user that this is ok and then it may take a few seconds for the device to actually work out the location) you need to provide a function that will be called when the location has been established.

After that accessing the location is easy just look at the coords.latitude and cords.longitude properties on the object that was returned to your callback function.

1<script>
2 function getLocation() {
3 if (navigator.geolocation) {
4 navigator.geolocation.getCurrentPosition(function (location) {
5 document.getElementById("latitude").innerText = location.coords.latitude;
6 document.getElementById("longitude").innerText = location.coords.longitude;
7 }, function (error) {
8 alert(error.code);
9 });
10 } else {
11 alert("location not supported");
12 }
13 }
14</script>
15
16Latitude: <span id="latitude"></span>
17Logitude: <span id="longitude"></span>
18
19<button onclick="getLocation();">Get location</button>
20

URL parameters with Javascript

So this took me by surprise the other day. JavaScript doesn't have a function to retrieve a URL parameter value. i.e. There is no Request.Querystring command! Of course it wouldn't start Request as it's executing on the browser rather than the server but you would have thought there would be a built in command to do it.

After a bit of searching though I came across this script that does it:

1// Read a page's GET URL variables and return them as an associative array.
2function getUrlVars()
3{
4 var vars = [], hash;
5 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&amp;amp;');
6 for(var i = 0; i &amp;lt; hashes.length; i++)
7 {
8 hash = hashes[i].split('=');
9 vars.push(hash[0]);
10 vars[hash[0]] = hash[1];
11 }
12 return vars;
13}

The function returns an array/object containing the parameters and their values. e.g. The following URL:

http://www.example.com/?Name=Tim&Sex=Male

Would return:

1{
2 "Name": "Tim",
3 "Sex": "Male"
4}

To use it in your code you would write

1var name = getUrlVars()["Name"];

And that's it

Hot Keys Made Simple

Hot Keys Made Simple

Previously I have blogged about how you can create keyboard shortcuts using JavaScript. In other words being able to add functionality to your web app for someone to do a ctrl+s. My previous example wasn't particularly hard and only used 10 lines of code, but this week I stumbled across a jQuery plugin that makes it easier.

http://code.google.com/p/js-hotkeys/

With this plugin, in just 1 line of code you can bind a function to a keyboard shortcut. What's more you don't even need to look up the correct keycodes as it takes a simple text parameters.

1$(document).bind('keydown', 'ctrl+c', fn);

Combine this with a function that just triggers a button click and you have some very cool advanced looking functionality written in around 5 - 10 minuets.

Add keyboard shortcuts to your web app

Keyboard shortcuts are common place in desktop apps, to such an extent that you would probably be surprised if holding ctrl+s didn't save a document, or if holding ctrl+n didn't do some kind of new action. But with website's its a lot less common. The bigger email providers all now provide the support, but for the sites produced smaller companies out there it's still not the norm. Actually adding the support for it though is actually quite straight forward.

In this example I'm going to use jQuery but it's just as easy in everyday JavaScript.

1var isCtrl = false;
2
3$(document).keyup(function (e) {
4 if(e.which == 17) isCtrl=false;
5}).keydown(function (e) {
6 if(e.which == 17) isCtrl=true;
7 if(e.which == 83 &amp;&amp; isCtrl == true) {
8 alert("Hello World");
9 return false;
10 }
11});

What is happening here is relatively straight forward. When you hold a key down, JavaScript will pick up an event that says which key was pressed by it's number. However what it can't do is pick up a combination, so if you do a ctrl+s what you get is two events (one for the ctrl and one for the s). So on every keydown if it's a ctrl we set the variable isCtrl to true, then on the next keydown we know it's a combination. The keyup detects the end of the ctrl being held down and sets the variable back to false.

The return false, when we've detected a ctrl+s is also very important as what this will do is stop the browser from carrying out any shortcuts it may have had for that combination.

So there we have it, in around 10 lines of code you can add some functionality to your web app, that seems really advanced but is actually really really simple.

Doloto

Doloto

Meant for Web 2.0 Apps that use a lot of JavaScript, Doloto will speed up the download time of all the JavaScript by basically removing anything that isn't initially needed and replacing it with stubs. It will then download in the background or wait until it is first called. The result, a seemingly much faster Web App for the user.

For more info have a look at the Doloto page on Microsoft's Research site or head over to the download page on MSDN.