The HTML5 Diaries – Part 5 – Manipulating the DOM

This is the fifth of six blog posts which are looking at the Microsoft 70-480 exam. Have no idea what this is all about? Click here. Are you doing the exam and want to start from the beginning? Click here. These blog posts are to be used as a companion to the videos produced by Microsoft and are the notes I have been taking from watching the training videos on the Microsoft Virtual Academy.

This blog post will look at using Javascript to manipulate the Document Object Model (DOM). In particular, I’ll look at querying the DOM, manipulating the DOM and responding to events.

If you’re going to use Javascript to modify your HTML, you’re going to first need to specify what bit of your document you want to edit. To do that, you’re going to have to query the DOM. This isn’t exactly hard. There are four Javascript functions that are mentioned on the training video.

These are generally used by creating a variable, and then assigning it the value that’s returned from the methods that are listed below. You’ll also need to invoke these methods by preceding them with a “document.”. You should have something that looks a bit like this.

var tagline = document.getElementById();

Easy enough stuff. So, those functions you should know…

getElementByID();

This basically sets the element that you’re going to modify based upon the id you gave it in the HTML markup. You put the ID name between the parentheses in speech marks, and you preface the ID name with a period.

getElementsByTagName();

This allows you to select all elements in your document based upon the kind of element it is. So, if you wanted to edit all list items, you’d pass the name of the element (li) in speech marks, minus the arrow signs.

querySelector();

Query Selector allows you to select the first element in your document that matches a criteria that you specify in the parentheses of the querySelector(); method.

querySelectorAll();

querySelectorAll() works like QuerySelector(), except with this you can select every single element that matches the criteria you specify.

With that all sorted, we can now move on to slightly more interesting stuff. Manipulating the document object model. So, let’s look at some simple manipulations. Say you’ve used a querySelector to select an ID, and you’ve assigned it to a variable called “thisID” and you then want to play around with that? Add some text and whatnot Easy.

Now, it’s worth noting that there are a lot of things you can do to manipulate your DOM with Javascript. I’m only going to mention a few choice functions.

thisID.innertext(“Changed”);

Here, you’re changing the text that is found between the start and close of the tags of the element you’re editing.

thisID.classname(“item”);

Here, you’re changing the class name of the item to something totally different. If you want to, you can also use this:

thisID.classlist.add(“item”);

A few other useful methods mentioned in the course videos are:

container.removeChild();

This method allows you to remove a child element from your HTML document.

document.createElement();

Here, you’re creating an element for you document. Specifying text content and IDs are sorted with the createTextNode and .id methods.

container.appendChild();

This method is rather useful. It basically allows you to insert a child element to the end of a node. This can be useful when you’re doing stuff like adding list items and stuff.

Finally, I’m briefly going to talk about responding to events. Javascript is an event driven language. This means that the running of the program is contingent on these things called “events”. These might be a click of the mouse or a press of a key on the keyboard.

So, this code might look a bit familiar:

<button id=”but” onclick=”handler();” > …

function handler() {
// do stuff
}

But that’s not really a good style. At least according to Jeremy Foster and Michael Palermo. They argue it’s best to use a programatic event handling style. So, what’s the difference? Have a look at this code.

<button id=”but”>

function handler() {
//do stuff
}
var b = document.querySelector(“#but”);
b.addEventListener(“click”, handler);

What we’ve done here is create a function that does what we want it to do when the event happens, but not used an onclick parameter in the HTML. Rather, we’ve added our event the Javascript way; By selecting the ID of the button, and then creating an event listener that calls the Handler function when a click is made on that button.

And that concludes this brief introduction to DOM manipulations using Javascript. I mention this a lot, but HTML, CSS and Javascript are huge technologies and there’s an awful lot of stuff I have likely missed. I’d honestly recommend you check out the Mozilla Developer Network for further reading.

Any comments? Feedback? Thoughts? Leave them in the box below.

The HTML5 Diaries – Part 4 – Javascript Core Capabilities

This is the fourth post in this blog series, covering the Microsoft 70-480 HTML5 certification. This blog post will discuss Javascript. If you have no idea what this series is about, and want to know more about the Microsoft 70-480 certification, click here. If you want to go to the first article in the series, click here.

So, Javascript… It’s a weird language. It’s got nothing to do with Java, but is called Javascript. Its proper name is “ECMAScript”, but acronym ECMA doesn’t exist anymore. It’s got its share of warts and carbuncles. However, it’s not all bad. It’s known as the assembly language of the internet. We use it for adding interactivity to web pages. There are cool libraries like knockout.js and jquery. You can write server side code with it, using node.js. Javascript is cool.

And if you’re going to develop HTML5 applications you’re going to need to know it. I’m only going to talk about the basics of the language here. Declaring variables and arrays. Manipulating arrays. Methods. Functions. Object oriented programming in Javascript. Nothing too heavy. Javascript is a big language, and it’s a lot to cover in one blog post. If you want to read more, be sure to pick up a copy of Douglas Crockford’s “Javascript: The Good Parts”. It’s nice and concise, and it gives a good low down of the language. Also, Crockford is the guy behind JSLint; A cool little site that allows you to do a static analysis of your code to get an understanding of its quality.

With all that said, let’s begin.

Javascript is a dynamic, weakly typed language. What does that mean? Well, if you’ve ever used Java, C or C#, you might have noticed that you declare a variable with a type (bool, string, char, int) and if you have an integer, you can’t force a string in there. Javascript isn’t like that. The way you declare a variable is a little bit different too:

var a = 10;

Here, you’ve created a variable called ‘a’ which holds a value of ten. If you wanted to, you could later assign ‘a’ a value that might be a string, or boolean value. Javascript is cool like that, y’see. We’re going to talk about arrays a bit more now. Arrays are basically lists of variables. You can declare them really easily.

var a = [];

Populating arrays is simple too.

var fruit = [“apples”, “oranges”, “lemons”, “kiwi”];

And, JavaScript has a lot of cool little methods that allow you to manipulate and interact with these arrays. So, suppose you want to echo out every single element in that fruit array you created before?

log(fruit);

All elements echoed out will be comma separated. Want to echo every element in that array in alphabetical order? That’s fairly easy.

log(fruit.sort());

The next two examples will make sense if you’re familiar with the concept and the terminology of “The Stack”, but for this example, I’ll spare you the computer science lecture. Suffice to say that if you want to add elements to the array, you “push” it onto the stack, and if you want to remove an element from the array, you “pop” it.

A quick demo. Popping the stack:

fruit.pop();

And pushing an item onto the stack:

fruit.push();

Now, suppose you wanted to merge your fruit array with a vegetables array? Easy as pie. Just use the concat method.

fruit = fruit.concat(vegetables);

If you wanted to select all elements in an array in between two indexes, there’s a function for that.

fruit = fruit.slice(0, 1);

And if you want to replace a couple of elements, you can simply splice them.

fruit.splice(1, 2, “chocolate”, “cake”);

Another cool thing that you can do to an array is change every element in the array with the map function. This sorta works a bit like Select in C#, and can be used as follows:

fruit = fruit.map(function (i) { return i.toUpperCase();});

Here we’re going through every element in the array and then capitalizing it. Easy stuff.

If you wanted to go through every element in the array and only return elements that match certain values, you can use the filter function. So, let’s return every element that begins with ‘a’.

fruit = fruit.filter( function(i) { return i[0] === “a”; });

If you wanted to see if all the elements in your array met a certain criteria, you can use “every” function. This returns a boolean value that tells you if the entirity of the array met the criteria or not.

log(fruit.every(function (i) { return i[0] = “a”;})

Here, we’re determining if every element begins with an ‘a’. If it doesn’t, fruit.every will return a “false” value.

log(fruit.some(function (i) { return i[0] = “a”;})

This is like above, but it returns true if some element in the array meet that criteria. And finally, there is the forEach function. This basically works like a for-loop. So, suppose you wanted to loop through your array and say what fruit you’ve got in it? Easy.

fruit.forEach(function (i) { log(i); });

The next thing I’m going to talk about is functions. Functions are basically re-usable snippets of code. You create them, and then you define the tasks that each function will perform. And then you call them when you need them. Easy really. And it allows you to write cleaner code, as you’re not writing different pieces of code to do the same thing.

So, functions are really easy to make. Suppose you want to write a function that will log “Hello Mum” whenever it’s called? Well, first you’d tell the Javascript interpreter that you’re creating a function. To do that, you’ll type “function”. Then you’ll give it a name; The more descriptive the better. Ideally one that’s in camel case (all words
concatenated with the first letter of each word uppercase”. Then, in parentheses you tell it if you’re going to be passing it a parameter. Then you create some curly braces where you’re going to store your instructions and in between those curly braces, you’ll tell the interpreter what you want to do with this function. So, let’s bring that all
together and create a function.

function HelloMum (){
log(“Hello Mum”);
}

Simple, right? Now, let’s talk about scope. Examine this code:

var x = 10;

function AddX () {
var y = x + x;
return y;
}

What do you think will happen here? Well, it’ll basically return “undefined” because the function cannot access a variable that’s not within the function itself or hasn’t been passed to the function as a parameter. If you wanted to have the function access ‘x’, you’ll need to put it between those parentheses in the function declaration.

Finally, I’m going to talk about bringing this all together and writing Javascript in an object oriented fashion. So, what is Object Oriented Programming? It’s a way of structuring code that allows for readability and reusability, whilst organizing functions based upon the type of tasks they do. It’s a complicated concept that’s hard to explain, and different programming languages do object oriented programming in different ways. Some use classes (Java, C++, C#, Ruby) whilst others use prototypes. Javascript is an example of a language that uses prototypes to create objects.

With that said, let’s create an object.

var dog = {};

Now, it looks a bit like an array, but instead of using square brackets, we’ve used curly braces. Now, let’s assign some variables and functions to our dog object. You can do either do this inside or outside of the object definition. You can use:
var dog = {};
dog.name = “Red Dog”;
dog.kind = “Kelpie”;
dog.from = “Australia”;
dog.bark = function () { log(“woof”); };

There’s another way to define an object in Javascript. It’s using something called “Object Notation” and here you’re defining your object variables and functions within the curly braces.

var dog = {
name : “Red Dog”,
kind : “Kelpie”,
from : “Australia”,
bark : function() { log(“woof”);}
}

You’ll notice that the variable names aren’t instantiated with the var keyword, and that each thing in the object declaration is delimited by a comma.

And that concludes this blog post. Any questions, comments or feedback, leave it in the box below.

The HTML5 Diaries – Part 3 – Advanced Layouts and Animations

This blog post covers the third module in the training course for the Microsoft 70-480 exam. We’ll be talking about using CSS to layout the content of your HTML document, along with using advanced features of CSS, including transforms and animations.

If you have no idea what any of this is about, click here to read more about the Microsoft 70-480 certification. If you want to start from the beginning of the course, click here. If you want to read the previous post in the series, click here. This blog series aims to be a companion to the training videos that are on the Microsoft Virtual Academy web site. Anyway, let’s begin.

CSS3 has heaps of new features that allow you to better lay out your document, and we’ll get to these in a second. But, first let’s talk about how we used to lay out things in a web page back when Marilyn Monroe wasn’t a quote on a facebook page and everything was black and white.

Some people thought it was a good idea to use tables to do all their layout. I’m totally serious. Now, this is bad idea. It’s bad for search engine optimization. It’s bad for developers, who have to write lots of horrible code. And it’s just… Not semantically nice. It reads badly. Blegh. Thank god we’ve moved on.

People eventually caught on that CSS can be useful for laying out documents, and we started doing things like this:

.centered {
display: table-cell;
min-height: 200px;
min-width: 200px;
text-align: center;
vertical-align: middle;
border: 1px solid black;
}

Now, the problem is that this code isn’t exactly descriptive with what it does; Display: table-cell? What does that do? I’m not even using a table!

That code, is not good code. It doesn’t make it clear what’s happening. It screams of hackyness. Now, good code isn’t just if it compiles, or renders, or is valid CSS. Good code is readable code. Good code is explicit. Explicit is always better than implicit.

You know how I mentioned HTML5 and semantics tags a few blog posts ago? Well, that’s a driving thing with HTML5. Making code just a bit… Y’know. Clearer. More explicit. Good CSS3 will do what it looks like. Which is kinda cool.

I’m going to mention one thing before I move on; You’ll see a lot of tags going forward that are prefaced with a ‘-ms’. Yep, these are vendor specific tags. They are still valid CSS3 though. If you’re developing just for Windows 8, you only have to worry about using the ‘-ms’ tags.

So, the first advanced layout technique we’re going to look at is called FlexBoxes. Check this out:

.flexbox #flexbox {
margin-top: 200px;
display: -ms-flexbox;
width: 100%;
-ms-flex-pack: end;
border: 1px solid gray;
}

Here you’re creating a Flexbox. Any idea what they are? No? The are basicaly flexible boxes that give you control over child elements and the remaining space. These are massively useful if you’re creating user interfaces. Most of the CSS properties here should be fairly familiar. The only ones I’m going to clarify are “display”, which is where you’re telling it that you’re telling the browser that you’re making a flexbox, and -ms-flex-pack, which says how you’re going  to distribute surplus space.

There are also Flexing Flexboxes. Confused? These are basically like before, but the child elements within the boxes flex in order to assume some of the surplus space. You make these by calling a property that’s simply called -ms-flex and is passed three parameters. The first specifies the relative space proportional to the rest of the element. The second is the recommended size of the child element (you can just put a zero here) and the third is auto. And you use it just like a normal CSS property.

And let’s not forget Wrapping Flexboxes. They are like the first example, but you’ll use the -ms-flex-wrap. These allow you to wrap text, so that you can present things as columns or rows. Another useful instrument in your user interface design toolbox.

I’m a little bit conscious here that I’ve not explained Flexboxes perhaps as well as the subject deserves. Fortunately HTML5 Rocks have a great article on FlexBoxes. Check it out here. It’s rather good.

Moving on, you can also use CSS to layout things in a grid. Now, grids are the basis of all design. Think of a site you use regularly. Reddit perhaps? Facebook? Your online banking? When designing the user interface of that web application you use, someone actually sat down and drew a bunch of grids. From there they added detail and little embellishments of design, until it started to look like the website you use today. Grids are very important, and it’s cool that you can easily make them in CSS3.

Anyway, grids. So, here’s how you actually make one.

#grid {
display: ms-grid;
ms-grid-columns: 1fr 1fr 1fr;
ms-grid-rows: 1fr 1fr 1fr;
}

So, I just made a grid with three rows and three columns. Easy. Notice how I used ‘fr’ as a unit of measurement? That means fractions. Yep, all this stuff is relative.

Now, we’re going to talk about using CSS3 to make your application a bit more theatrical. Yep, we’re talking about those cool animations and transforms that came about recently.

So, suppose you have a DIV called “transformme”, in which there’s a picture that you want to enlarge by a factor of two whenever you’re hovering over it with your mouse? Simple. Just use the “transform” CSS property.

#transformme:hover {
transform: scale(2);
}

Simple. How about moving it whenever your mouse hovers over it?

#transformme:hover {
transform: translate(50px, 50px);
}

Want to rotate it a little bit? No worries.

#transformme:hover {
transform: rotate(10deg);
}
Notice there that we’re rotating by degrees; Not by inches, centimetres or any other measurement.

Sometimes, you want to delay a transform or once a transform has occurred, have it hold its new position. Well, the ‘animation’ property handles all that for you. This is a little bit tricky, and therefore I’m going to refer you to Smashing Magazine who have an excelent article on CSS3 animations.

The skinny is this. You have these things called Keyframe rules, and this is what they look like.

@Keyframes dostuff {
0% {
transform: rotate(10deg);
}
50% {
transform: rotate(10deg);
}
75% {
transform: rotate(10deg);
}
}

So, it’s fairly obvious what’s going on here. We have a Keyframes rule, and you’re specifying actions to do at each milestone within the animation. Now, suppose you want to call this animation when you hover over an element in your HTML document? Easy.

#dosomestuffhere {
animation: dostuff 5s forwards;
}

So, you’re using the animation properties, and you’re passing it three parameters. The first is the rules specified in the @keyframes bit. The second is the duration of the actual animation. The third parameter is telling it to hold the position it is in. See! You can make cool animations without Javascript.

And that concludes this blog post on advanced layouts and animations. Any questions or feedback, please leave it in the comments box below.

The HTML5 Diaries – Part 2 – Cascading Style Sheets

This is the second blog post covering the Microsoft 70-480 HTML5 certification. These are my notes for the videos  covering module two, which looks at CSS, giving a rather general covering of CSS selectors, combinators and properties. If you have no idea what I’m on about, click here to learn more about the Microsoft 70-480 certification. If you want to read the previous blog post in the series, click here.

If HTML is the roof and the walls of your house, then CSS serves as the wallpaper and the shingles and the tiles. Basically, it  applies formatting and decoration to the structure you set out in your markup. CSS works out what it’s going to apply formatting to with these things called selectors.

Type selectors are a kind of selector and they work in a really simple manner. What they do is they apply formatting to every single element of the  type you specify, within your HTML document.

So, to make every single <p> element in your document turn red, you type:

p { color: red; }

Note that “color” is spelled in the American fashion. If you’re from the UK, Ireland, Canada or the Antipodes where you  spell words slightly differently to American English, please take note here.

Class selectors apply formatting to every single element that has a class declaration. So, if you have a bunch of  headers with a class of “arabicacoffee”, you would format those headers by writing in your stylesheet:

.arabicacoffee { color: red; }

Applying formatting to elements with a certain ID is fairly similar. Except, instead of starting your stylesheet selector with a period, you start it with the pound (hash) sign.

#thisisanid { color: red; }

Attribute selectors allow you to apply formating to elements based upon certain attributes. So, suppose you have a table which is declared as so:

<table data-author=”Quentin”>

You can apply formatting to that object based upon the “data-author” attribute really easily:

[data-author=Quentin] { color: red; }

With attribute selectors, you can also apply formatting to elements that start or end with, or contain certain characters.

[data-author$=tin] { color: red; }

This applies styling to anything with a data-author attribute that ends with “tin”.

[data-author^=Q] { color: red; }

This applies formatting to anything that starts with ‘Q’.

[data-author*=q] { color: red; }

If there’s anything in your HTML document that has a data attribute which has the letter ‘q’ in it, it will now be colored red.

You can also format your HTML document by using pseudo classes and pseudo elements. These are a bit tricky, and there are an awful lot of them. I won’t be writing about them all, but you can read more about them here.

li:hover { color: red; }

You might have seen something like this before. Basically, when your mouse pointer hovers over that element, its color will change to be red. Another useful pseudo-class allows you to format certain elements, based upon the order in which they’re presented.

li:first-child { color: red; }

This formats the first element in a list. Suppose you want to edit the nth element in a list?

li:nth-child(2) { color: red; }

This is fairly self explanatory. It’s worth noting that this pseudo-class isn’t zero indexed, so you’ll start counting from 1, not 0. This might trap a lot of people who do programming, particularly in languages like C, Java and PHP which are zero indexed.

Pseudo-Elements are similar to pseudo classes. Suppose you want to apply formatting to the first letter of a <p> element. Simple.

p::first-letter { color: red; }

This will format the first letter in a <p> element as red. Easy enough stuff. I’m not going to list every single one,  but you can read more about them here.

This module also talks extensively about combinators. These allow you to apply styling to elements based upon how they  relate to other elements.

Descendant combinators allow you to apply styling to sub-elements. So, suppose you have a bunch of <p> tags buried  within a div with an ID of “DiV”? You can apply formatting to those tags by using:

#DiV p { color: red; }

Those paragraph tags will be formatted, regardless of how buried it is within other elements. Similarly, a child combinator will format an element, but it has to be a direct descendant. Child combinators are used like so:

#DiV > p { color: red; }

The general sibling combinator works by styling the first element mentioned and the next element of the type specified. Confused?

p ~ li { color: red; }

So, this will format the first <p> element, and every <li> element that follows it. Adjacent siblings work in a similar  manner, but they must follow and be adjacent. They look a bit like this.

ul + div { color: red; }

And that concludes selectors and combinators. But what about properties? These are the things that define what formatting should take place. Now, it’s worth noting that this is a huge field. A HUGE field. CSS has existed since 1996. To put that in context, CSS was created when I was 5. That means there’s a huge overhead of things to learn. It’s a big language. And no. I’m not going to cover it in this blog post. However, I do highly recommend that you grab a copy of ‘HTML and CSS, The Complete Reference’ from McGraw Hill. It’s a massive, weighty tome and it costs a fair bit of cash. But it covers absolutely everything. If you want to buy it from Amazon, please consider buying it through this referral link.

By now, you’ve probably worked out how to color an attribute. You have the declaration. Then the curly braces. Then “color: “. Then the color you want to give it. And then a semi colon. Obvious stuff.

Now, in CSS there are a lot of ways to do the same thing. You can set a color with the English name of the color. You can write a hex value. You can write an RGB value. You can write a HSL value. And then you’ve got HSLA and RGBA. Now, you’ll never remember every single hex and rgb value in the world and I’ve got no desire (or time) to write down what each one is. When looking for the hex or rgb value I need, I always end up using Color Schemer.

HSL stands for hue, saturation and lightness, and is a new feature in CSS3 that allows for a slightly more intuitive specification of color values. However, it’s worth noting that support for it can be a bit… Well? Patchy. Y’know with certain older browsers not really supporting CSS3 and HTML5 all that well. You can read more about it here.

CSS3 also has a rather nice feature that allows you to set the opacity of an object that’s significantly semantically nicer than the older ways of defining opacity.

p { opacity:0.4; }

Fairly self explanatory stuff.

The next part of the training course (and which my notes are about) refers to CSS properties that deal with how text is formatted.

The font-style property is fairly obvious. You’re saying how you want your text to look. In this case, it can either be bold, italic or oblique. If you want to set the contents of every <p> element, simply use:

p { font-style: italic; }

The font-weight property allows you to set how “heavy” a text is. It can either be normal (the default), lighter, bold or bolder. You can also set the weight of the font with number values. Font-weight values start at 100 and end at 900. You can use font-weight like so:

p { font-weight: bold; }

Font-size allows you to set the size of the text that you wish to format. If you’ve ever used Microsoft Word or any similar word processor, this will be immediately apparent to you and I won’t insult your intelligence by explaining more than I have to. Just look at the example below.

p { font-size: 24px; }

Font-size is really flexible with what you can throw at it; Inches, centimetres and pixels. It’s all good.

Line-height allows you to set the spacing of an element. It works just like font-weight and you just specify a height like before. So, if you want to double space your text, just write:

p { font-size: 24px; line-height: 48px; }

Font-family allows you to specify the font of the text that you’re formatting. Now, you have to be careful with this as this depends on fonts being present on the client’s computer. So, best just to keep it simple. Using this property isn’t hard. Just use:

p { font-family: “Helvetica”; }

CSS3 has this cool thing called font-faces. What do they do? They allow you to specify a font that’s located in a publicly accessible folder, and then allowing you to use it in your web page. You effectively become a server of fonts. You can read more about them here.

The last thing talked about is box properties. You know how I mentioned how CSS is big? Well, the amount of things you can do to format the space around text and images is… Well… Immense.

Before I go any further, I’m going to mention that you really need to learn about the box model to make heads or tails of what I’m about to discuss. Have a look here. But, can I recommend another book? Design For Hackers is actually amazing. I’m not a design oriented guy (I much prefer hacking about with back end stuff) that book gives me a grounding in design principles. It also taught me to respect the thought and hard work that goes into design. I honestly cannot recommend it enough.

Anyway, so you have the box model. Which you totally know by now, because you read up on it. Right? Anyway, have a look at this.

#thisdiv { padding: 20px; border: 20px solid black; margin: 20px; offset: 20px; }

Obvious stuff. Now, you can apply formatting to certain parts of the box model. So, if you want to format the left hand side of the border, and nothing else? Easy.

#thisdiv { border-left: 20px solid black; }

You can see certain patterns emerge, right? And this ends my notes for the second module on the 70-480 HTML5, CSS3 and Javascript training course. Jeremy Foster and Michael Palermo go on to talk about setting visibility of an element, but not in any great deal, so I’m not going to talk about it much. I will suggest you look into the display, visibility, white-space and overflow CSS properties, as these were quickly mentioned and may come up on the test.

I hope you’re finding these notes useful. If you have any questions, comments, or feedback, please leave them in the comments box below.

The HTML5 Diaries – Part 1 – Semantic Markup, Forms, Media and SVG

This blog post will cover the topics discussed in the first module in the Microsoft HTML5, CSS3 and JavaScript video training course for the 70-480 exam. If you have no idea what’s going on, click here to have a look at the first post in this blog series which discusses setting up a development environment, registering for the exam and the online training content. Then, watch the video lessons for first module of the course, which is delivered by the charming and charismatic duo of Jeremy Foster and Michael Palermo.

Once you’ve gotten round to doing the courses, you might benefit from reading my course notes that are below. Most of the content below is gleamed from watching the lessons and making notes, and also from third-party resources that I like, such as dev.opera and the W3C Consortium. If you have any issues with the content or want to make a correction, please drop me an email or leave me a comment in the box below.

Semantic Tags

And thus, we begin. So… Semantic tags. What are they? Semantic tags are a new feature of HTML 5 that allow you to structure your code in a manner that represents how your site will actually look and are the first topic covered in this module. So, what do they do? They basically formalize design patterns. So, what does that actually mean?

Let’s think of a fairly popular website. How about BBC News? It has a navigation bar. It has articles. It has content within those articles which is kinda, but not really related to the actual content. It has structure. And most web pages are a bit like that. They have some form of structure and layout.

Semantic tags allow you to describe that structure and the content of your web page. And for the most part, they’re fairly easy to grasp.

Element

Level

Purpose

Article

Block

Independent content, such as blog posts and articles.

Aside

Block

Content that’s slightly related to main content

Figure

Block

This groups standalone content. The example given in the W3C documentation groups a video and a figcaption (I’ll get to those in a minute).

FigCaption

Text

This captions a figure element. Fairly self explanatory.

Footer

Block

This will go at the bottom of your page and will contain cool stuff like copyright information and author attribution.

Header

Block

Introductory headings or navigational aids.

Hgroup

Block

Groups a set of heading elements from <h1> to <h6>.

Nav

Block

For site level navigation.

Mark

Text

Text to be referenced or highlighted

Section

Block

Grouping of content with a heading. Sorta similar to chapters.

Time

Text

Represents date and time.

Semantic tags are generally a good idea, because they allow you to cleanly express the types of content of your page without actually having to look at any content. And they’re useful. Learn them.

Before you go any further, you might want to have a look at the W3C specification for HTML5. It’s a little bit dry for some tastes, but it’s incredibly thorough and detailed and covers extensively semantic markup. It’s also worth noting that the venerable Smashing Magazine has a rather good article about semantic tags, written by none other than the legendary Bruce Lawson. Have a read.

Forms

Forms have seen a massive overhaul in HTML5, and are discussed extensively in module one of the 70-480 training course. So, what’s new? Well, you can do cool stuff like this now.

[sourcecode]<form>
<input type=”text” required />
</form> [/sourcecode]

Yep, you saw that right. In a deviation from previous versions of  HTML, there’s an attribute (“required”) that is just floating out there.Does it make you feel a bit uncomfortable? Well, you can always do this.

[sourcecode]<input type=”text” required=”required” /> [/sourcecode]

What about if you want to have a placeholder in the input box? That’s simple.

[sourcecode] <input type=”text” required placeholder=”example@example.com” /> [/sourcecode]

Now, let’s look at some really cool stuff. Suppose you want to have a box where people can leave their phone number?

[sourcecode]<input type=”tel” pattern=”\d\d\d-\d\d\d\d\” /> [/sourcecode]

See what I did there? I also specified the input to have a type of “tel”. That’s basically for phone numbers. There are other input types, such as “email” and “url”, and they’re fairly obvious. Inayaili de León wrote a good blog post about using the latest features of HTML5 in making your web forms. You might find it useful.

You’ll also notice that in the “pattern” attribute, I wrote a regular expression which all input will be validated against. And you can customize your regex based upon the input that will be submitted.  Speaking of which, you can read all about the different things you can throw at a HTML5 form right here.

One other thing about Regex. Yes, it’s hard. No, it’s not particularly fun. But it’s important. Zed Shaw has a rather good book called Learn Regex The Hard Way. It’s free. Have a look. You might also want to have a look at this blog post by Staffan Noteberg.

Music and Video

HTML5 is kinda cool in the respect that it does multimedia very, very well. You can embed an MP3 with just a single line of code, and it just works. You no longer have to deal with Flash, or Shockwave, or Quicktime, or any other ghastly framework from the late 90’s that refuses to die.

Want to embed an MP3? Simple.

[sourcecode]<audio src=”yourmp3.mp3” controls> </audio>[/sourcecode]

That’s fairly self-explanatory, and ideal if you’re embedding within a HTML5 desktop or mobile app, like a Metro, Phonegap or Blackberry 10 application. If you’ve developing for the web, you might want to do something like this.

[sourcecode]<audio controls>
<source src=”source.ogg” />
<source src=”source.mp3” />
Your Browser Doesn't Support HTML5 Audio. Get with the times man!
</audio>[/sourcecode]

Why is that example ideal for a web application? So, you’ll probably notice that there are two audio sources there. That’s because different browsers support different codecs. If you use just one file format, you might see yourself running into a few cross-browser compatibility issues. Although, if you’re developing an application for Metro, you’ll likely be safe with just MP3/MP4. Embedding video is more of the same. You can insert it into your application like so.

[sourcecode]<video src=”video.mp4” controls ></videos>[/sourcecode]

And if you’re embedding video in a website, you can use…

[sourcecode]<video loop autoplay muted controls>
<source src=”video.webm”/>
<source src=”video.mp4”/>
Oh noes! Your browser doesn't support HTML5 Video.
</video>[/sourcecode]

Notice how I passed some parameters in the opening video tag? I won’t insult your intelligence by explaining what they do. That said, you probably should know what they do. You can find out more by having a butchers over here.

Also note that the file types of the video in thetags. Webm video is used extensively by Google Chrome, Opera and Firefox, whereas MP4 is used by most other browsers. If you want your video to work nicely cross-platform, it’s probably a good idea to use a variety of file formats.

Canvas

Canvas is fairly cool. What does it do? Well, the clue is in the name. Like a painter’s canvas, you can draw shapes. Except with Canvas, you do it programatically. With JavaScript! Yay! You could probably write a really, really long book about Canvas if you wanted to (and, let’s face it, someone probably has). But I don’t want to do that. To be honest, I’d rather just write a really short example and explain what’s happening, and then point you in the direction of some further reading. So, let’s get started.

[sourcecode]<canvas id=”testcanvas” width=”200” height=”200”>
</canvas>[/sourcecode]

So, here you’re creating a Canvas with an id of “testcanvas” (don’t forget to give it an ID. It’s important. Also, remember that it’s case-sensitive), a width of 200 and a height of 200. Fairly simple stuff. Now, here’s where it gets tricky.

[sourcecode]
<script>
var tstcnvs = document.getElementById(“testcanvas”);
var ctx = tstcnvs.getContext(“2d”);
ctx.fillstyle = “rgb(0, 0, 255)”;
ctx.fillrect(10, 10, 180, 180);
</script>
[/sourcecode]

Line one declares a variable called “tstcnvs”, which refers back to the canvas you created before. Line two declares a variable called “ctx” which then calls getContext which returns all sorts of fun methods to create geometric shapes and stuff and tells it that you’re dealing with 2d shapes. Line three then says that you’re going to colour your shape blue. Line four paints the rectangle by calling the fillrect method. It passes four parameters to this method. The first is the X coordinate. The second is the Y coordinate. The third is the height. The fourth is the width.

That was nothing more than a cursory glance at Canvas. But it’s an integral part of HTML5 and you should definitely look into it further. The Mozilla Developer Network is a good resource and they have heaps of stuff about Canvas, amongst other things. Opera has some good documentation regarding it too!

SVG

The last part of this write-up covers SVG. Scalable Vector Graphics basically allow you to create computer graphics, but with XML. Yep, you heard that right. Using XML to create graphics. There are some instances where you might want to use SVG over Canvas. There are some circumstances where you’ll want to use neither, as plain old HTML/CSS will do the job.

With that said though, I’m not really going to go into SVG that much. It’s only briefly mentioned in the online tutorial and it’s a fairly huge topic. Instead, I’m going to talk about where you’ll use SVG over Canvas, and vice versa and where you should not use SVG. I’ll also talk about where you can learn more about using SVG to make graphics.

Here’s what Opera (the guys who make the web browser that’s really popular in Belarus) have to say about the ideal use cases of Canvas and SVG.

You should use Canvas for:

  • Interactive image editing: cropping, resizing, filters (think red eye removal, sepia, colorize, etc.)
  • Generating raster graphics: data visualizations, data plots, rendering fractals, function plots.
  • Image analysis: read pixels to gather data for histograms, color usage, and anything else you can imagine.
  • Rendering game graphics, such as sprites and backgrounds.

You should use SVG for:

  • Resolution-independent Web application user interfaces.
  • Highly interactive animated user interfaces.
  • Data charts and plots.
  • Vector image editing.”

Some research has shown that Canvas scales better than SVG and generally renders a bit faster. It’s also worth noting that it’s generally not a good idea to use SVG to do stuff that you can do with CSS, such as page layout and rounded borders. For some further reading, have a look at this MSDN blog post.

Being able to create graphics with SVG is without a doubt a good skill to have under your belt, and odds are good it’ll come up on the 70 – 480 exam so you might want to brush up on it. A cursory glance on Amazon suggests that there are a good few tomes on the subject. In the meantime, have a look on MDN and dev.opera for more information.

Fin

And that’s that. If you have any comments or feedback, please leave it in the comment box below. The next post will be about CSS3 Selectors and Style Properties.