HTML5 Series – Array

If your going to do any sort of JavaScript programming it’s not going to be long until you have to work with an array, so there’s a few array functions you need to know about.

Push and Pop
Push and Pop are functions that add and remove items from an array. The easiest way to understand what they are doing is to imagine your array as a stack of paper. When you push and item onto the array it’s the same as putting it on the top of your pile. When you Pop an item off it’s the same as taking the top item from the pile.

        var myArray = [] // Declare a new array
        myArray.push("Red");
        myArray.push("Blue");

        var value1 = myArray.pop();
        var value2 = myArray.pop();

        alert(value1); // should alert the value Blue
        alert(value2); // should alert the value Red

Foreach loop
Probably one of the most useful functions for an array is the for each loop. A for each loop is essentially calling a function for each item in the array (hence for each). This is particularly useful in all kinds of scenarios.

        var myArray = ["blue", "red", "green"];

        myArray.forEach(function (x) {
            alert(x);
        });

Filter
As the name suggests filtering is a way to find items in your array. If you know C# then it works in a similar way to a lambda expression. The filter function takes a parameter of a function. Like the forEach loop the function is called on each item in the array, the function must then returns either true or false depending on if the filter criteria matched.

In this example notice that the result of myArray.filter is being assigned to another variable. This is because applying the filter wont actually remove items from the myArray array.

        var myArray = ["blue", "red", "green"];

        var results = myArray.filter(function(x) {
            if (x == "blue")
                return true;
            else
                return false;
        })

        results.forEach(function (x) {
            alert(x);
        });

Some, Every
The some and every functions can be used to see if some items in the array match a criteria of if all of them do. They return either true or false.

Like the filter function, a function is passed as the criteria and returns either true or false.

        var myArray = ["blue", "red", "green"];

        alert(myArray.some(function (x) {
            if (x == "blue")
                return true;
            else
                return false;
        })); // Alerts true as 1 item in the array is blue

        alert(myArray.every(function (x) {
            if (x == "blue")
                return true;
            else
                return false;
        })); // Alerts false as not every item in the array is blue

Concat
Concat is used to combine 2 arrays into 2 new array.

        var myArray = ["blue", "red", "green"];
        var myArray2 = ["yellow", "orange"];

        var myArray3 = myArray.concat(myArray2);

Slice
Slice lets you create a new array from an existing by letting you specify the start and end item. Those items and the others between then form the new array.

        var myArray = ["blue", "red", "green"];
        var myArray2 = myArray.slice(2, 3); // selects red and green

Splice
Splice can be used to add and remove items in an array. The function has the syntax:

arrayName.splice(index, how many, items to add);

Note: the index value starts at 0.

For example in our colour array we could add yellow and orange in between red and green with the following:

        var myArray = ["blue", "red", "green"];
        myArray.splice(2, 0, "yellow", "orange");

        myArray.forEach(function (x) {
            alert(x);
        });

Alternatively we could replace red and green with yellow and orange.

        var myArray = ["blue", "red", "green"];
        myArray.splice(1, 2, "yellow", "orange");

        myArray.forEach(function (x) {
            alert(x);
        });

A couple of others

Sort Sorts the array into alphabetical order
Reverse Reverses the order of the array
Advertisements

HTML5 Series – Error Handling

One thing you can say for certain about writing code is at some point your going to write something that error’s. It may be picked up in code reviews, or by a tester, and then fixed but for certain as you are human at some point you will make a mistake. What’s important though is what happens after the mistake.

If your a C# developer then good news JavaScript has the same try, catch, finally functionality that C# has and it works in the same way.

Wrap you code that could error with a try statement and curly braces and following it add in a catch statement with the code that you want to execute in the event of an error. Finally if you want some code to execute either way after both, place this in the finally block.

try
{
    functionThatDoesntExists();
}
catch (err)
{
     alert(err.message);
}
finally
{
    //Code to execute at the end
}

Notice the catch section is passed a parameter and I am then alerting a property of this called message. The error parameter can be useful for debugging what actually went wrong and contains a few other parameters.

  • Description
  • Message
  • Name
  • Number
  • Stack

Sometimes you may also want to cause an error to be thrown. You may be asking why, but consider people calling your functions may in-fact pass values that are not valid. You could detect this and throw an error containing some useful information before there incorrect parameter values causes your code to error and a less helpful message given.

var err = new Error(1, "Oh dear, that's not going to work"); // First parameter is the error number, second is the message
throw err;

HTML5 Series – Web Storage

One of the best benefits of HTML5 particularly for Web Apps is the ability to store data locally within the users browser. This means in many places you can speed your Web App up by fetching data once and then retrieving it locally in the future, rather than going back to a server each time.

There are 2 types of storage available localStorage and sessionStorage. The simple difference is that localStorage doesn’t expire while sessionStorage expires at the end of the users session.

Both types store data in a key/value list and could not be simpler:

// local storage
localStorage.variableName = value;

// session storage
sessionStorage.variableName = value;

One thing to note though is you can only store text. If you want to store something more complex the simple solution is to convert it to and from JSON. E.g.

var myColours = [ 'red', 'blue', 'green', 'yellow'];

// Save to local storage
localStorage.colours = JSON.stringify(myColours)

// Retrieve from local storage
var retrievedColorus = JSON.parse(localStorage.colours);

jQuery ajax

If you want to dynamically load content into your page chances are your going to need to do some sort of request to a server in the background. The simplest way of doing this is to use jQuery’s ajax function.

Here’s an example of a GET request and a POST request:

        $.ajax({
            type: "POST", // Set the HTTP type to POST
            url: "/serviceurl.aspx", // URL of the service
            data: "{data: [{"Field1": 1}] }", // Data to be posted to the service
            processData: false, // If set to true the data will be processed and turned into a query string
            success: (function (result) {
                // Result of the service call
            }),
            error: (function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            })
        });

        $.ajax({
            type: "GET", // Set the HTTP type to GET
            url: "/serviceurl.aspx", // URL of the service
            dataType: "jsonp", // Set what type of data you want back
            success: (function (result) {
                // Function that will be called on success
            })
        });

HTML5 Series – Fonts

It’s an all to common story, designer designs a website hands it to a developer who then goes, “what kind of font is that?” and get’s the response of some completely unheard of name. The developer then try’s to explain what a web safe font is and they agree to use Arial.

With CSS3 custom fonts are now a reality. On the item you are styling you still set the font family in the same way but additionally in your CSS you specify a @font-face rule so the browser can find out what the font is. The @font-face rule should specify a name and the src of the font. e.g.

@font-face { 
     font-family: myFont;
     src: url('myFontFileName.ttf');
}

One point to note different browsers support different font type. Luckily though you can specify multiple sources for your font.

HTML5 Series – Grid

There was a time when an HTML page layout mainly consisted of tables, and lots of them. Tables went inside other tables and complex layouts were achieved through the use of colspans and rowspans. The only problem though was it was a mess.

By using tables the HTML mark-up was dictating the design/layout of the page and if you ever wanted to change anything it was a huge task to undertake. Since then the world has moved on and now most webpages consist mainly of div’s. But what if you did want to quite a rigid layout with columns and rows?

HTML5 introduces the Grid style through CSS. Your page can still consist mainly of div’s (or anything for that matter), but in your css you set a display property of grid (for now in IE it’s -ms-grid). You can then specify a grid-columns and grid-rows property to create a grid within your div.

Child items can be placed in grid cells through grid-row and grid-column properties in the CSS, and if you want something to span more than one cell you can use grid-row-span or grid-column-span.

If you’ve done any XMAL programming (WPF/Silverlight/Win8/Windows Phone) then this should all sound very similar to XMAL’s Grid control.

The example below creates something like this:

GRid

    <style>
            /* Set a grid with 3 columns and 2 rows */
            div {
                display: -ms-grid;
                -ms-grid-columns:200px 200px 200px;
                -ms-grid-rows:200px 200px;
            }

            /* Position the child div's in the grid */
            div:nth-child(1) {
                -ms-grid-row: 1;
                -ms-grid-column: 1;
            }
            div:nth-child(2) {
                -ms-grid-row: 2;
                -ms-grid-column: 1;
            }
            div:nth-child(3) {
                -ms-grid-row: 1;
                -ms-grid-column: 2;
                -ms-grid-row-span:2; /* The middle cell spans 2 rows */
            }
            div:nth-child(4) {
                -ms-grid-row: 1;
                -ms-grid-column: 3;
            }
            div:nth-child(5) {
                -ms-grid-row: 2;
                -ms-grid-column: 3;
            }

            /* Add a border to the cells */
            div>div {
                border: solid 1px black;               
            }
    </style>
    <div class="myGrid">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>

It’s also worth noting that the column/row sizes can be specified using fractions rather than fixed sizes. e.g. The following will produce a grid 600px wide where the middle column is twice the width of the other 2.

    <style>
            /* Set a grid with 3 columns and 2 rows */
            div {
                display: -ms-grid;
                width:600px;
                -ms-grid-columns:1fr 2fr 1fr;
                -ms-grid-rows:200px 200px;
            }
    </style>

For another great example check out this hands on page from Microsoft Hands on: CSS3 Grid

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

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

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.

    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (location) {
                    document.getElementById("latitude").innerText = location.coords.latitude;
                    document.getElementById("longitude").innerText = location.coords.longitude;
                }, function (error) {
                    alert(error.code);
                });
            } else {
                alert("location not supported");
            }
        }
    </script>


    Latitude: <span id="latitude"></span>
    Logitude: <span id="longitude"></span>

    <button onclick="getLocation();">Get location</button>

HTML5 Series – Video

Like Audio embedding Video in an HTML5 web page is really simple to do and has a very similar syntax.

The video tag can contain multiple source tags to specify videos in different formats as not all browsers support the same ones, and some text to be displayed if the browser does not support any. The video tag can also have a controls element specified to instruct the browser to display controls for the playback.

<video controls>
    <source src="URL of video.mp4" type="video/mp4">
    <source src="URL of alternate video.ogg" type="video/ogg">
    Your browser doesn't support viodes
</video>

You can also set the following tags:

autoplay Specifies that the video should begin playback immediately
loop Sets the video to repeat
muted Mutes the audio on playback
poster Specifies an image to be shown what the video is downloading
preload Specifies if an how the video should be loaded when the page loads

It is also possible to control a videos playback through JavaScript. You can reload the element, play and pause that track.

var v = document.getElementById("myVideo");
v.play();
v.pause();
v.load();

HTML5 Series – Audio

Traditionally if you wanted Audio on your page you would embed it in a Flash object. But when Steve Jobs declared that the iPhone would never support Flash or any other plug in’s, there was suddenly a demand that browsers would need to support this natively and in a consistent way between browsers.

In HTML5 we can do this using the Audio tag. e.g.

<audio controls>
     <source src="url of the file" type="audio/mp3">
     Your browser doesn't support audio.
</audio>

The above example demonstrates setting the file source for the audio with the source tag, the controls tag tells the browser to show audio controls and there is also some text that will be displayed if the browser doesn’t support audio.

It is also possible to set multiple source tags to reference different file formats as not all browsers support the same ones. Alternatively when setting just one source, a src tag can be placed on the actual audio node rather than as a child element.

Other settings which could be set include:

autoplay – determines if the file should start playing on the page load
loop – specifies that the file should repeat when it’s finished
preload – instructs the browser to start downloading the audio file when the page has loaded

HTML5 Series – Columns

I’m not sure I’ve ever needed to add columns where text flows from one into the other, but if your doing Windows 8 development where you would want a sideways scroll rather than vertical this could be quite useful.

To create columns using CSS3 you simply set the columns property to either the number of columns you want or the width each columns should be. e.g. This would produce 4 columns.

<style type="text/css">
        div {
            columns: 4;
        }
</style>

There are a couple other properties that are also quite useful when using columns.

Column-Gap Specifies the size of the gap between columns
Column-Fill Can either be set to auto where columns are filled sequentially and have different lengths, or balance in which case the text will be balanced so each column is even. The default is balance.