Using Bootstrap to build a simple UI

In my previous post about Using Jasmine to Test JavaScript, I used an example to convert Length for different Units (LengthConverter.js). Next, I decided to go ahead and build a simple UI for the Length Conversion, using Twitter Bootstrap.

Version 3 of Twitter Bootstrap is different from the previous versions, as it is a mobile-first framework and can claim to be one of the best CSS frameworks for building responsive website designs. The reason I used it was because it would be really fast and easy to put a nice UI together.

To get started download the latest version from http://getbootstrap.com/ and use the basic template to start working with a minimal Bootstrap HTML5 document.

The main components of Twitter Bootstrap V3 are:

  • Fluid grid system that scales up to 12 columns (example)
  • CSS base for typography and UI components with consistent styles (docs)
  • jQuery plugins to build an interactive experience on the website (docs)

And honestly, the docs / examples on the site (provided by links above) are so good that you probably don’t need any other reference tutorial.

So here is my Length Units Conversion UI built with bootstrap (http://manishchhabra.github.io/JasmineExample/)

Unit_Conversion

Source code: https://github.com/manishchhabra/JasmineExample

 

Tagged ,

Using Jasmine to Test JavaScript

Jasmine is a behavior-driven development framework for testing JavaScript code. It does not rely on browsers, DOM, or any JavaScript framework. It has a clean, obvious syntax to be able to write tests easily. [http://pivotal.github.io/jasmine/]

The best way to start with Jasmine is to dive straight into examples.
Example: 1 – Use ‘describe‘ to define a test suite and ‘it‘ to define a spec

describe("A simple test suite - is just a function really!", function() {
  it("A simple test spec - is also just a function!", function() {
    var a = 12;
    var b = a;
    expect(a).toBe(b);
    expect(a).not.toBe(null);
  });
});

Example: 2 – I am taking an example to convert length for the following units:

Kilometer, Meter, Centimeter, Millimeter, Mile, Yard, Foot, Inch, Nautical mile

I want to define a convert function
function convert(number, baseUnit)” which will take a number and a baseUnit as an input,
for example convert(1, ‘Kilometer’) and return back a hash of all converted units
example return: {‘Kilometer': 1, ‘Meter': 1000, … }

So in a true TDD (Test Driven Development) style I am going to write my tests first and then write code to make them pass. For this example I am actually going to create a video, which should show you how to get started with Jasmine on your machine and write specs..

Jasmine has a rich set of matchers (used in spec for example toBe( ), not.toBe( ), etc) included. You can refer to the Jasmine doc for full reference, but here are some of them for reference…

  • toEqual – represents the regular equality == operator
  • toBe – represents the exact equality === operator
  • toBeNull: tests the actual against a null value
  • toBeUndefined – tests the actual against “undefined”
  • toBeDefined – opposite of the JS “undefined” constant
  • toMatch – calls the RegExp match() method behind the scenes to compare string data.
  • toBeLessThan/toBeGreaterThan: for numerical comparisons.
  • toBeCloseTo: for floating point comparisons.
  • toThrow: for catching expected exceptions.

And yes, in my LengthConverter example I could also use toBeCloseTo( )  instead of comparing the units with crazy decimal numbers… I will be updating that example soon and will add a UI to it as well.

Source Code: LengthConverter.js, LengthConverterSpec.js

 

Tagged , ,

Geolocation in HTML5

What?

Geolocation is a technology to retrieve current geographical location of a user.

Why?

So consider an example that you are visiting a city for the first time and looking for sight-seeing locations close to your hotel. However, you do not know where to go and which places to look for. Therefore, it will be helpful if you have some application that can help you locate such places and provide feedback for the same. In that case you as a user will have to allow the application to detect your location and provide you that feedback.

An application like map can also use Geolocation to give you direction to a target location.

How?

The HTML5 Geolocation API uses certain features, such as Global Positioning System (GPS), Internet Protocol (IP) address of a device, nearest mobile phone towers, and input from a user, in the users’ device to retrieve the users’ location. The users’ location retrieved by using the Geolocation API is almost accurate depending upon the type of source used to retrieve the location.

There is a really good demo of HTML5 Geolocation here (http://html5demos.com/geo).

The Geolocation API provides the following methods:

1. getCurrentPosition(successCallback, errorCallback, options)

Used to retrieve the current geographical location of a user.

successCallback

as the name suggests is a callback function when the geolocation is successful at locating the current position of a user. It takes position object as an argument. This position object specifies the current geographic location of a user as a set of geographic coordinates. Here is the list of properties available

  • coords.latitude
  • coords.longitude
  • coords.accuracy
  • coords.altitude
  • coords.altitudeAccuracy
  • coords.heading
  • coords.speed
  • timestamp
errorHandler

is a callback function to handle errors that may occur while retrieving the location of a user. The third parameter,

options

specifies a set of options, such as timeout for retrieving the location information. Both of these are optional parameters.

2. watchPosition(successCallback, errorCallback, options)

The function returns a watchId and calls successCallback with the updated coordinates. It continues to return updated position as the user moves (like the GPS in a car).

3. clearWatch(watchId)

Stops the watchPosition() method based on the watchId provided.

Before retrieving the users’ location by invoking getCurrentPosition() we can also check whether the browser supports the geolocation feature.

Listing 1: Consider the following code snippet to check whether the browser supports the geolocation feature:

if (navigator.geolocation) {
  alert("Your browser supports geolocation.");
} else {
  alert("Your browser does not support geolocation.");
}

Listing 2: Consider the following code snippet for retrieving the users’ location by using the getCurrentPosition() method:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(userPositionSuccess, userPositionError);
} else {
  alert("Your browser does not support geolocation.");
}

function userPositionSuccess(position) {
  alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
}

function userPositionError() {
  alert("There was an error retrieving your location!");
}
Handling Errors

At times, the user may not provide the permission to access his location. Or the error may also occur when a user checks the current location on a mobile device and the device goes out of coverage area or the network connection is timed out. We can handle different types of errors by using some pre-defined error codes.

  • PERMISSION_DENIED
  • POSITION_UNAVAILABLE
  • TIMEOUT
  • UNKNOWN_ERROR

Listing 3: So we can now can improvise on our errorHandler callback function to give more appropriate message:

function userPositionError(errorObject) {
  switch(errorObject.code) {
    case errorObject.PERMISSION_DENIED: alert("User denied the request for tracking the location"); break;
    case errorObject.POSITION_UNAVAILABLE: alert("User's location is not available"); break;
    case errorObject.TIMEOUT: alert("The request to retrieve user's location is timed out"); break;
    case errorObject.UNKNOWN_ERROR: alert("An unknown error occurred"); break;
  }
}

Ok! That should be good enough to make use of Geolocation in an application now.

P.S. Just don’t use javascript alert in your real app, that was just to demo the function.

Tagged ,
%d bloggers like this: