What do you want to learn? Leverged jhuang@tampa.cgsinc.com Skip to main content Pluralsight uses cookies.Learn more about your privacy Practical HTML5 by Gill Cleeren HTML5 has been around now for some time. But how do you get your head around all that comes with it? The answer is by doing. In this Practical HTML5 course, you can do exactly that by building a site from scratch, adding new HTML5, CSS3, and... Start CourseBookmarkAdd to Channel Table of contents Description Transcript Exercise files Discussion Learning Check Recommended Creating a Site Using HTML5 Module Introduction Hi, and welcome to this Pluralsight course titled Practical HTML5. My name is Gill Cleeren, you can contact me via twitter via @gillcleeren. As the title of this course implies, this is a course aimed at teaching you all the aspects of HTML5. But in a very practical way. Along the way, we will be building a website which uses the most commonly used features of HTML5. So by the end of the course, we'll end up with a fully working website that you can use as a starting point for your own HTML5 endeavors. In this very first module, titled Creating a Site Using HTML5, we'll be exploring some basic topics around HTML5. To be more precise about what will be covered in this module, let's take a look at the outline first. As mentioned, the course is very practical so we will be building a site with HTML5 together. I think it's a very good idea to start by exploring what we will be working towards. So I'm going to show you the end result first. I'll then give you a high level overview of what HTML5 really is and why it is such an important thing for the web today and tomorrow. After that somewhat more theoretical part, we'll start creating our site. I'm going to start by building the skeleton for a couple of pages. When we reach the end of this first module, we'll have an understanding of what HTML5 brings to the table. We'll already have a couple of pages created in a somewhat rough first version. We will of course, continue working on the site in the following modules to make it more polished. Looking at the End Result I named this course Practical HTML5. I think the best way of learning is by doing. This course is accompanied by addendum material. Which gives you the ability to follow along with most of things I'll be doing throughout the course myself. Another aspect I find important is seeing how everything fits together to get the bigger picture. For this reason I'm creating together with you a fully working website. You won't be seeing any stand-alone features. After you see a feature in the slides, we'll immediately add it to our site to make it more functional. I hope you'll have a good time learning HTML5 and its companions. Now that I have teased you for some time already about the site we'll be building together, it's time to explain what we will be working towards. Like most developers, I like coffee. I love coffee. Without it, I can't kick off my working day. That's why I choose to build throughout this course an imaginary coffee bean store named Joe's Coffee Store. As the name implies, Joe is selling coffee online, and he wants to give his visitors the best experience possible. For this reason, he asked to build a site, which is using the newest features available, so we will answer his question by building an HTML5 focused website. Note that in this course I'm focusing on the HTML5 side of things, so I won't be using any beacon system to store orders or read database to fetch our coffee types. Amongst others, we will be building, of course, the home page, a page where Joe's coffees are listed, a detailed page per coffee, the ability to drag coffee to the shopping cart, and a checkout page. As here most of you are somewhat familiar with HTML and developing for the web, so I'm not going to spend time explaining the basics of HTML. Instead, we are focusing on the new features which HTML5 brings to the web. To create Joe's Coffee Store, we'll be using most HTML5 features. This includes the new HTML5 elements and their attributes, as well as the new form controls. We'll look at how we can use most of the new CSS3 features to make layout of the site even easier than before. For example, we'll look at the new CSS3 selectors which were added. We'll also integrate audio and video into our site to showcase different types of coffee. Joe's Coffee Store is going to use both the canvas and SVG for advanced graphics scenarios. We'll use both approaches to create sales chance for the different coffee types. I already mentioned that we'll have a shopping cart in the site as well. We'll be building the shopping cart using two features that come with HTML5, namely web storage and the drag and drop feature. We'll also give the user an easy way to find the physical Joe's Coffee Store using geolocation, which also comes out of the box with HTML5. As we can see, we'll have a lot of work adding all these features into a real working site. Before we continue, I want to give you a peek at the working site, which we'll build together in this and the following modules. Demo: Looking at the End Result In the first demo of this module, I'm going to show you the finalized Joe's Coffee Store website. So this is the site that you'll be working on throughout the modules of this course. Let's take a look at the pages which have been implemented, and let's see what their functionality is. Let's take a look at the pages which have been implemented, and let's see what their functionality is. store, so Joe's Coffee Store, in a specific font. There's also a search box here on the right. Then we have the navigation, and the background is a gradient. I have a couple of pages here. I'm going to show you those in just a minute. Then we have a lead image here and also an image for the coffee of the month. A bit lower here we see a multicolumn text, which is basically now a lorem ipsum text, but this could be a welcome text explaining what Joe's Coffee Store is all about. Here on the right we have an extra block which contains some extra links, perhaps some news updates about Joe's Coffee Store. Still on the home page, Joe's Coffee Store also lists a couple of bestsellers, so its top selling items. There are a couple of coffees here, and we can click on Add To Cart button, and there are also a couple of accessories. Here on the bottom of the page we have Joe's Coffee Store's physical address, a copyright notice, and also the time at which this page was rendered. As mentioned, you have a couple of pages that we'll be implementing throughout this course. One of those pages is the Our coffees page. The Our coffees page is basically where the shopping will be done. In one of the later modules, we'll see that we can actually use drag and drop to add products to our shopping cart. I'm going to show you this very quickly. I'll take a coffee, and I'll drop it onto the shopping cart, and that coffee will be added there. You'll see that this is done using the drag and drop API in HTML5. Then we also have the Find us page, and this page shows a map to show you the route to Joe's Coffee Store, so the physical store again, based on the location of where you're currently at. We also have a Checkout page, which is basically a large form where the user can enter his details. All of these fields are actually using quite a number of HTML5 features. These are the pages that we'll be building throughout this course. You may not have noticed it, but they are actually using quite a lot of new HTML5 features we'll discover in the upcoming modules. Let's go back to the slides for now. HTML5 Overview Now that we have seen the finished site, it's time to start building the site ourselves. All the features you saw were purely done using nothing but HTML5's out of the box features. I haven't used any third party frame to do all this. All comes with the HTML5 standard. I think no HTML5 course is complete without showing the new HTML5 logo somehow. So there it goes Just like the many new HTML5 features, it also has a new fancy logo. You're only staring at a logo for too long. Instead, let's see what HTML5 brings to the table. HTML5 is the newest version of HTML. It actually replaces HTML4 which was born many, many years ago. Even before the year 2000. So effectively this means that we have been using the web for so many years with nothing more than what HTML4 could give us. HTML5 is much more than HTML4. For one, the HTML5 standard is not just to new elements, it's effect a collection of standards. HTML5, is therefore not only HTML. Instead, also Javascript and CSS3 are part of the new definition. HTML 4 was quite limited. And yet, we have survived on this small standard for so many years. How did we manage? The answer was plug-ins. The web became interactive through the use of plugins such as Silverlight or Adobe Flash. With HTML5, plugins are not going to be needed anymore. The standard is trying to make everything which was possible before with plugins only available out of the box. For the web user this is good news since he doesn't have to make sure that he has the newest version of the plugin installed. Now for the web developer this should also mean less headache. We're living in a world of devices. The use of websites from devices is higher than it is from desktop PCs. We therefore need to make our sites so that they are displaying information correctly, both in the desktop browser and on smaller screens. We all know that Windows isn't the only operating system being used today. HTML5 is one solution of building cross-platform applications. Most of the features we'll see in this course will work in most major browsers as we speak. One important thing to note here is that HTML5 sites mostly still work in all the browsers. The experience won't be optimal but most things will still render correctly. The HTML5 definition was created by the W3C and other working groups. Along the way, they sort of merged their efforts and HTML5 is the result of their work. On this slide here, I've summarized most features that come with the HTML5's tenant. Of course, we have the new HTML5 elements, form controls, and attributes. Very often people think HTML5 is nothing but some new tags. Well they couldn't be more wrong. There's the new embedded CSS3 standard. We have support for rich graphics with a Canvas and SVG. The Canvas is using a JavaScript API to create interactive graphics. Whereas SVG allows us to create vector-based drawings. Audio and video are baked into the platform as well, allowing us to playback media without the need for plugins to be installed on the system. There's now the ability to work with files and storage. The file API allows JavaScript to work with files. Using the storage API, we can store data on the local device which gives us many more options than what cookies allowed us to do. It's also possible for HTML5 apps to use the offline support. Using the support, users can run a cached version of the web application. Drag and drop allows us to pick up elements and drop them on a different location. Microdata allows us to nest metadata into webpages which in the end can be used by browsers to give users a richer browsing experience. These are the most important features which are included in the HTML5 definition. There are other features, which you'll often come across, which aren't really part of the HTML5 Standard, but are very often seen as being a part of it. The Web SQL and the Indexed Database API allow us to work with a database implementation from a webpage. I've already mentioned the ability to work with files from JavaScript, again this isn't really part of HTML5 itself. And the same goes for the background worker API, which allows us to create long running tasks from the browser. In a later module, I'm going to cover the geolocation API, which itself isn't part of HTML5 either. This one, though, is very often considered as a real part of HTML5. Finally, Web sockets are again not really part of the HTML5 Standard, but are part of the new features we're getting with this release. In general, where there are features is part of the HTML5 Standard or not is not something that should keep you up at night. If the feature is there, and it is supported in most major browsers, there's no one stopping you from using it. Building the Skeleton Now that you have an idea on where to situate HTML5 and that you know what it is and isn't, it's time to get practical. As promised, we should end up with a basic HTML5-based site at the end of this module, so let's get straight to it. We're going to start building the skeleton of the HTML pages. As such, an HTML5 page is nothing more than an HTML page you have probably already worked with. Like previous versions of HTML, HTML5 pages contain tags. Tags can be seen as building blocks for the pages. There are quite a few tags available, each with their own functionality. Some tags have a visual meaning while others don't. A tag such as h1 or an input tag are visual tags, while a meta tag used to indicate metadata for the page is not a visual tag. Using the tags, we build up the HTML document. The HTML code we see here on this slide shows a very basic page with a head and a body inside of HTML tags. Inside the body, we create the structure of the page. Using just plain tags, we won't get very far. We'll need some CSS to enhance the visuals and JavaScript to add interactivity. We can link JavaScript and CSS files with this page using the script and link tags as shown here. In the previous slide, I haven't talked about a big difference HTML5 and previous versions. Remember in HTML4 we used to have to include a complex DOCTYPE declaration as shown here. This was pretty complex so that almost everyone copy-pasted it from somewhere. With HTML5, this is now simplified to just DOCTYPE html as shown below. I already mentioned that very often people associate HTML5 with the new tags which were added. Like we already saw, there's much more to it than just some new tags. However, it's interesting to start by taking a look at these new tags, which are now supported. Recurring from HTML4, which had a number of well-known tags out of the box, these include the doctype, the anchor tag, the paragraph, ul and li for lists and list items, and so on. The div, or division, is a very popular tag, which is very often used in combination with CSS for layout and styling purposes. The object tag also used to be in the high demand. It was the tag used to embed Silverlight or Flash plug-ins. The form, of course, is also very common. It's the tag which makes the web interactive, allowing users to send and request data. Inside the form, we use the input tag, which has a number of types defined, such as text for a plain text box or radio for a radio button. Let's now look at the newly added tags. We're going to start by looking at the newly added so-called semantic tags. Now what is a semantic tag? Let's take a look at that first. I've placed a quote on this slide here. A div is just a div. Now what does that mean? We all know that modern web pages are very often constructed using div elements. In itself, a div is just a block with no meaning at all. Now by looking at web pages, most pages have a header div, a footer div, and so on. So this div then gets its meaning commonly through the use of an ID or a class. Now for software such as a crawler or screen reading software, it's not always easy to identify which div contains which particular information. Sometimes the ID of their header div is head. Sometimes it's header. Sometimes it's page header. While we as humans can easily figure it out, it's harder for an automated process. The problem with these divs is that by default they have no semantic meaning, so a div remains nothing more than a div. Now enter the new HTML5 semantic elements. With HTML5, a number of semantic elements have been added. The name of the elements, in most cases, gives away what they are to be used for. For example, a header tag is to be used for page or block header information. This means that inside the header element we can place the logo and the navigation menu, for example. However, what the header doesn't do is adding any visual behavior. It's not because we place element inside of a header that this content will be centered on the screen and made bold, for example. Far from it. The header behaves just like a div, but instead it gives its contents semantic meaning, and that goes for most tags that you see here on this slide. In the following slides, we'll take a look at some of these tags in a bit more detail. Let's start with the article and the header. Like already mentioned, the header is commonly used to place page or block header information within. In this example here, we are placing the header within another new element, the article. The article is, as the name implies, commonly used to wrap things such as a blog post or a user comment. According to the HTML5 spec, it's a piece of content which can stand on its own. The new footer element is used to wrap page footer information. This often contains contact information, a physical address, and so on. In the sample here, we have a page on our site with a footer, and in there we have contact information for the creator of the page. The section tag is a very interesting one. It's probably the one which lies the closest to the original div, and it's very often used where a div would normally have been used. However, there's a difference. The HTML5 spec describes the section as a piece or block of content on the page. If the container is there just for layout purposes, we should use a div instead. So if the container is there for layout purposes only, then use a div. If, however, the content is a separate section on the page, use the section element. So in the sample here, we have a number of coffees with their description. A section is better than a div here since the separation is based on content, not styling. Another new tag with no visual representation is the address tag. As you can defer from the name, it's used to wrap address information. But again, it is not because content is inside an address tag that it is laid out differently. It's just semantic meaning. We're saying that the content is effectively an address. The aside tag is another interesting one. As the name implies, it's used to wrap content which is related to the main content. So on a page we can have an article with the main content, and next to that we can have some related information, which is not really part of the main block of content. That related information should then go in an aside tag. In the sample here, we have an article about coffee, and inside of the aside block we have some trivia about coffee. The new figure and figcaption are often used incorrectly. The figure tag is to be used to wrap an image which is related to the main content. It's not correct to replace each image on your page with a figure. Only use the figure when it's referred to from the content. The figcaption can then be used to add some information below the image. Here in the sample code we have a figure wrapping indeed an image, and a figcaption is used to add some text below the image. The summary and detail tags are a bit of an edge case. For starters, I wouldn't recommend using them since at the time of creating this course they aren't well supported in most browsers. So what is their purpose then? A summary details block should be displayed as an expanding element. The summary is always shown, and the detail is opened when the summary is clicked. Here we see a screenshot of the summary details in Chrome, which is currently the only browser supporting these tags. The elements we have seen so far are all block elements. Next to the new block elements, there are some new inline elements being added to HTML5 as well. As a small reminder, an inline is typically displayed without starting a new line first, whereas block elements normally start and end with a new line. The new inline elements include the mark, the meter, the progress, the output, and the time. Let's take a look at the most relevant ones in a bit more detail. And let's start with the mark tag. The mark tag is typically used to highlight content. You could use this to draw the user's attention to something, but also to highlight content based on a search query answered by the user. In the sample here, we're using the mark tag to emphasize that the store will be closed. The default highlight color is yellow, which you can change through CSS. The next element is the meter tag. As the name implies, this tag is used to represent a value within a range or a fractional value. Typically, we could use this to show a percent of completion, how much space the user still has in his cloud storage folder, for example. Here in the sample we're using the meter tag to indicate how strong a particular type of coffee is. This is indeed a fractional value. Now closely related to the meter is the progress tag. You would use the progress tag to specify progress of a task. As you can see from the sample on the slide here where we are using the progress tag to show how far the user is in a checkout process that the meter has a visual representation, and it is dependent on the browser. The last tag to take a look at is the time tag. The time tag has again more a semantic meaning. It has no visual representation. It, for example, doesn't change do you want it to display a clock. What it does do, however, is making sure that the time indication is machine readable. For example here in the demo code, we are using the time tank to make sure that, for example, a search engine knows the date indicated with the text Christmas Eve. Now that you've seen several new tags in HTML5, it's time for the first real demo, and in this demo we are going to create some pages, making use of the new HTML5 tags. Demo: Creating the Pages Using the New Elements In the first demo of this module we've seen the finalized version of Joe's Coffee store. Let's now start building that website. Now typically before any code is written a design of a mock up is made and that is exactly what I've done here as well. I have created using Balsamiq some mockups for a couple of pages we are going to create. And then we'll start adding the code for those pages. This is the mockup for the index or the landing page. You'll notice the logo. Joe's coffee store navigation, a couple of images, so delete images, the text that will later make multi column, some links to news items, and then we have the coffee best sellers, and at the bottom of the page we had the footer with the address and the copyright notice. Let us now create the code for this page. Just to set things clear, the goal of this first demo is building up the skeleton, so we don't be adding any layer yet. That will be done in module two. So I'm now in Visual Studio. I'm going to start by adding a new HTML page to my solution. And I'm going to call that Index. Now, Visual Studio presents us with a blank HTML five page, and we can see that when we look at this very simple doc type declaration. So now I'm going to focus mostly on adding content to the body of the page. Let's take a quick look at the mock ups again. So the first thing I'm going to add is this image here as well as this Joe Coffee Store header. The first thing I'm going to be pasting in is the header. Notice that I'm using a header tag here. As explained in the slides this has mostly a semantic meaning. It doesn't add any layout whatsoever to my page. Inside the header I use a plain old div, within there an anchor tag, so a link surrounding an image and also a SPAN which contains the text Joe's Coffee Store. We're going to skip for now adding the navigation and these two lead images here. We'll do that in a later module. Let's now focus first on these two blocks here. So, this welcome text, and this list of used items, so that related information. For the welcome text, I've used this section tech. I could've used a div if this block would be there just for layout purposes but here it actually has a meaning, saying that its contents belong together. That is why I used a section here. Next we will add that related information. For that I'm using the aside tag. Remember that the aside tag is mainly used for information which is related to the content, so to the main content here, but is not really part of that main content, it is related information. That is why I'm using the aside tag here. Now, I've come to the point where I need to add this entire bestsellers block with the coffee's header. For this block I've decided to began use a section, as you can see here. Again the reason is the same. I'm using a section because of the fact that all its contents is related, it is one block of related content that I'm going to be adding. First I'm going to add to my section a header. That would be the bestsellers at Joe's Coffee Store. Now, inside this bestsellers section I'm going to have several other sections. The start of it I'm going to have the coffee best sellers which contains all the coffees. Again, this nested section also has a header. And inside of it, I'm going to add the different coffees. I'm going to add the first coffee and I'm using for that coffee an article tag. Now, this may astonish you a little bit. Why is this an article? Now an article if you look it up in HTML five spec is basically an on itself standing piece of content. While an article can also be a product and that's exactly what I'm doing here. I'm inside the article tag, I'm using first a figure to surround the image. This is a little bit debatable whether or not a figure is really useful. As you may remember from the slides,. The figure is often used to end the images referred to from the main contents. That is not really the case here, so whether or not you should lay the figure here, it's a bit open for discussion. But let's put it there for now. And I have again, a header which contains the product article name, and then I also have a div, which will later become the button to add that product to the cart. The other products are of course the same. And as mentioned, I also had other sections, So, they are all within that main section here, bestsellers. If we go back to the mockups, we'll see that there's one more thing to add and that is the footer. Now, just like the header, the footer is another semantic element. Inside the footer, I'm going to add the address and the copyright notice, and finally, also, the time at which the page was generated. Now, for the address, I'm using the new address tag again. A tag with semantic meaning, meaning that its contents actually represents a physical address. I also need to add the copyright notice and the time the page was generated. The copyright notice is a very simple paragraph. The one containing the time on which the time was generated, actually uses the time tag. Again, a tag that gives the semantic meaning to its contents. There's one more tag I actually want to use on this page, and that is the mark tag. I actually want, in the welcome text, to highlight something, so that users will actually see this. And to mark the piece of content, I'm actually using the mark tag. which will highlight by default using yellow, its contents. If you save this and browse to this page, you'll see a very ugly looking page for now. So there we have the header, the welcome text, the highlighted text that I just headed with the mark tag. This is the site containing the news information. And then we have the bestsellers, which are all in article text. And an article tag is a block element, meaning that they're all by default listed below each other. And at the very bottom of the page, we have the footer which contains the address, the copyright notice and the page generation time. The second page you're going to work on is the coffee details page. As you can see, this page also has the same header. It can contain the name of the coffee, the larger image of that coffee, all the text explanation of that coffee, and the price and then at the bottom of the page we again have the footer. We're going to just add another new page which will be coffee details. And I want to start by adding the same header again. For similar reasons I'm going to add another section which contains all the coffee details. It is content that is mainly belong together. This section has of course a header, which is the name of the coffee. It also contains an image of the coffee, which is again wrapped in a figure tag. And notice that I also have a fake caption here to show some tags below the image. Finally, I have the entire coffee description inside of a div here. Let's take a look at this page in the browser. Again, it's looking pretty ugly for now. The final page we'll look at for now, is the all coffees page, which again contains a very similar header, and then a listing of different types of coffee, and the shopping cart on the right. Now, I have cheated a little bit, and I've pasted in the entire page already. So, let's take a quick look at it. It is pretty similar to what we've already seen. We again have the header at the top of the page. We have a section called, allcoffees, which will contain, effectively all coffees, as a header for that section. And then, each coffee is again wrapped in a different article tag. At this point, we've created the skeleton using the new HTML5 elements. One little thing I haven't mentioned yet, you can follow along with everything that I'm doing here. In the sample code that comes with this course, we can find to begin, as well as the end solution for each demo. Let's go back to the slides for now. Summary With the side skeleton ready, we have arrived at the end of this first module. The pages are still extremely basic, but we'll work on that, of course, in the next modules. Let's quickly recap what we have seen in this first module. We have seen that HTML5 is adding quite a lot of new features and is actually much more than just HTML. In itself, the HTML5 arsenal of available tags is dramatically extended. Many of the newly added tags are there to give semantic meaning. To the content they contain. In general, the HTML5 standard is a very strong evolution of HTML, and it enables us to build web applications of today and tomorrow. These sites not only run in a desktop browser. Indeed, with HTML5, we are ready to build web apps which run on many devices and platforms. I hope you've enjoyed this first module and hope to see you again in module two. Thanks for watching. Adding Some Basic CSS and JavaScript Module Introduction Hi, and welcome to the second module of this Pluralsight course titled Practical HTML5. My name is Gill Cleeren and you contact me via Twitter by @gillcleeren. In first module of this course, we have created, using the new HTML5 tags a very basic site, with some simple pages in there. In this second module, we will improve the visuals of the site skeleton using CSS3, and we will also include some very simple JavaScript already to make the site a bit more interactive. The agenda for this module is pretty much what I have just mentioned. We will start by taking a short overview of CSS. Note that we'll have a full module on the new things in CSS3 later in this course. Next, again as a short introduction, we'll see how we can make our pages more interactive using JavaScript. The first target of this module therefore is understanding what CSS is, and what it can do for our site. Understanding how to include some very simple JavaScript to make the site more interactive, is target number two. Adding Some CSS So far the pages that we have created in the first module aren't looking very good yet. You can really use some styling help here. In the first part of this second module, we will look at some basic CSS, which we need at this point in a demo, to make sure that we have a reasonable layout for our pages. In a later module, we'll learn what is new in CSS3, which is part of HTML5. I'm going to assume that you are familiar with the concept and advantages of CSS. CSS, or Cascading Style Sheets, allow us to group layout code in a central location, instead of cluttering our regular markup code with all these extra attributes. An added advantage is that we can easily make changes in one location, and all pages using the styles defined in CSS will be updated. Talking about styling in general, styling information can be added to HTML in three ways. The first one is basically inline. We then use the style attribute on the HTML element directly. In the style value, we can use CSS in the form of key value pairs. In the sample here, we are changing the color of this paragraph to blue using an inline style. I think it's pretty obvious that this type of styling isn't really recommended, since we aren't placing all of our style information in that central location. We're completely missing out on the reuse part of things. The second option is grouping our style information in the style block in the head of the page. While we are grouping the styles now, which is good, we still can't reuse our styles over several pages. The best option to work with CSS is using the link element. Using the link element, we can reference a CSS file in our page, as can be seen in the third sample that just popped up on the slide. Of course, more than one CSS file can be linked to the page using this approach. And since our styles are not defined in separate files, we can reuse these styles over several pages. Before we'll add styles to the pages we already created in the previous module, I want to make sure you're on board with the basic use of the CSS game. CSS itself is composed out of rules. A rule is in itself a combination of a selector and one or more style declarations. A selector is used to indicate which HTML elements are the target of the style declaration. We'll look at possible selector types in the next slides. After the selector, we can indicate what the style should look like using several style indications. And each declaration is basically a key value pair in the form of property, colon, and then the value. Each declaration must end with a semicolon. Since we often end up with a large number of declarations shorthand is often used. As you can see in the sample here, instead of creating a separate declaration for all properties we want to use, we can wrap them in a shorthand version. Let's break down a CSS rule, and let's look in some more detail at the CSS selectors. As mentioned, CSS selectors are used to select one or more elements on the HTML page, and on these elements the CSS rules will then be applied. We can make selections based on the tag name. In this case, all paragraphs on the page will be selected and their content will be set to green. We can also use the class name. In this case we need to prefix the class name with a dot. And if you want to be even more specific, we can use the ID of an element, and in this case we have to prefix with a hash sign. Selectors aren't limited to using just one single selection option. We can combine them. For example in this selector here, we're saying that we want to retrieve all elements with a class coffeeType applied on them, which are within a paragraph. Basically, this is a logical and operator which is applied on the elements. In this case we do not have to specify the space between the two selectors. If we want to be more specific again, we can use child and descendant selectors. An example of a descendant selector is shown on the slide here in the form of coffeeType, space and then the anchor tag. This selector will retrieve anchor tags which are a descendant of an element with a class coffeeType. If we add a greater than symbol, then we are creating a child selector. In this case the anchor tag should be a direct child of the element with the class coffeeType applied on it, otherwise it won't get selected with this selector. Next to the, let's say, regular selectors, there are also pseudo classes and pseudo elements. We'll see a lot more on these in a later module. For now, take a look at the samples here on the slide. Pseudo classes and elements allow us to make selections which would be quite hard if not impossible to make otherwise. The first child and the first letter are some examples here. But don't worry, we'll take a look at these in much more detail later in the course. With the selection made, we can then apply a style declaration. It's impossible, and I think it's also quite useless, to look at all styles that we can set. So a small sample should give you an idea on how they work. Very often, styles are applied on colors. For example we can specify that all h1 headers should have a specific color. Backgrounds are also typically controlled using CSS. Backgrounds have quite a few color properties, such as color, image, position and many, many more. We can specify them all separately, but we can also choose to use a shorthand version, which is the last sample you see here on the slide. Also text properties are often styled using CSS. Style information like the font size and font weight can be controlled quite easily. Also things like underline of text can be done with CSS, and you see a sample of that here on the slide. CSS is of course used for styling individual elements but it is also used to create layout for our pages. Before we start talking about layout, a little warning is in place. When creating a page layout, do not resort to using tables. It's bound to get you in trouble, it will be very hard to create a layout which scales well on different browsers, certainly on mobile devices. Another reason for not using tables is that a table will only be rendered after the closing tag is encountered, which is of course not a good thing for the layout of your page. If we can't use tables, what should we use then? So far with HTML, we've had a div element for layout purposes. Now in combination with CSS, this offers us all the fire power we needed to build a great-looking layout. Since HTML5 however, we have the ability to also use the new semantic elements such as the article, and the section, and they should be used wherever they can to add semantic meaning to the content. For the layout of individual elements, CSS uses the CSS Box Model. This model essentially says that each element has a number of layers around it. These layers allow us to create a border around the element, and allows us to define spacing between elements. The actual content is right in the middle, and it specifies a size using a width and a height. Quite often we don't use the absolute values, instead we use upper and lower bounds. The first layer we encounter then is the padding. Padding clears an area around the content. The next layer is the border, which goes around the padding, and of course also around the content. And the last layer is the margin, which clears an area around the border. When creating page layouts, we have to resort to some other CSS properties as well. CSS has display properties, which specify how an element is going to be positioned in the layout of the page. There are two possible options here, inline and block. As some elements are inlines and some are blocks by default and it's possible using CSS to overwrite this behavior. Inline elements are positioned next to each other, so basically on the same line. Typical inline elements include the span, the image, the anchor and quite a few more. Block elements don't want to be positioned on the same line by default, so what they do is taking up all the horizontal space. Any following content will be directed to a new line beneath the block element. The default block element is of course div, but also paragraphs, headers, articles, sections and many many more are block elements by default. To see how they behave, let's take a look at this drawing. The inline elements will place themselves next to each other until they have reached the width of their container. Whenever we create multiple block elements, each containing inlines, the block elements will position themselves below each other. Each will start a new line. The last thing I want to show you before we go and apply all this in the demo is the float. Looking at the HTML spec, a float is actually a box, which is shifted to the left or right on the current line, and other content may flow along the side of the float. When using float for example on a div, the element is laid out first according to the normal flow like we've just seen in the previous slides. Then it's actually taken out of the normal flow and shifted to the right or to the left. This allows us for example to create text which flows around an image, which wouldn't otherwise be possible to do. Floats are very commonly used to create a column-based layout, which is while we'll use it too. Next to float we can also use the clear. When we want to make sure that an element that follows a floating element sits below the floats, we can use the clear property. When using the clear value, we make sure that the element won't have others on its left or right side. Let me show you this in a small example. The layout we see here is a pretty typical web page layout with a header, main content, a sidebar, and a footer. To create this layout, we add a block element for the header which will use all possible space horizontally. Next we want the main content block to remain on the left. A block element by default doesn't allow this. So, we'll use a float here. The element is set with float left, meaning it's going to go to the far left side of the page. The sidebar, again a block element, now needs to go to the right of the content, which will work since we have marked it as being a float also. We again specify float left so that it will position itself next to the main content. Finally, we have a footer. The footer shouldn't use float but instead, we want it to take all available space on a new line. For this we use clear and specify the value to be both. This ensures that the footer element shouldn't receive any neighboring elements on either of its sides. Let us now go back to the demo, and we'll add CSS code to create the layout, and we'll also add some more HTML5 elements. Demo: Adding CSS to Our Site The goal of this demo is improving the layout of our site. We already have made the skeleton using the new HTML5 tags, in the demos of Module 1. In this demo I'm going to make sure that each element gets its correct position on the page, and for that I'm going to use some CSS. So what you see here is the current state of the index page, and we're going to improve that. As you can see in the head block of this page, there is currently no reference to a CSS style sheet yet. You've seen in the slides that there are several ways to include CSS in our pages. However the best one is using a separate style sheet and referencing that using a link tag in the head. I must confess I have cheated again in this demo a little bit, I'm not going to do it anymore, I promise. I'm not going to be typing all the CSS it would take us again too long. I have prepared the CSS and I'm going to take you through the creation of the layout of the page. So the first thing I'm going to do is drag that CSS file in Visual Studio into the HTML, and automatically Visual Studio is going to include this link tag referencing the layout.css, so the style sheet. Let's take a look at that CSS. Here we are in the CSS, and the first CSS rule that you see here is one which is applied on the body. If you think back what we saw in the slides, notice that there's no prefix before the body declaration here, I don't have a hash sign or a dot, it is simply body. That is because body is indeed an HTML element and therefore to select it I don't have to use any prefix. Inside the CSS rule, I have a couple of style declarations, which are saying that for example the width of the body should be 1000 pixels. I'm also setting the margin-left and the margin-right. I'm not using any shorthand for this one. And I'm also specifying the font family. Next I have a comparable rule for the header. And again I'm using the HTML element directly as the selector. Now I want to build up the content of my header. Remember that in the header we had the image, then I had a span containing the text Joe's Coffee Store, and that search input type that was on the far right. The first thing I need to do is I need to get hold of this header logo, and to do that I'm using the selector that is prefixed with a dot. So I'm using a prefix here to select a class. Notice then, I'm using a float, and I specify the value of this float to be left. What this will do is making sure that the entire header logo block is going to be shifted to the left. Now inside this class I had a direct child of type image, and I'm also using the direct child selector here to select that image and apply a style onto it. I'm giving that image a width and a height. The next thing I want to do is make sure that that search input type goes to the far right, and notice it also has a class applied to it named searchbox. In the CSS, I'm again using a class selector, so it's prefixed with that dot again, and then I specify that it should float to the right. This span containing the text Joe's Coffee Store needs to go to the left of the image we already have placed there. We'll change on this span later on, but notice for now it has an ID defined named headername. Now in my CSS, I can now use a selector based on the ID, so I prefix the idea with the hash sign. In here I specify some properties for the text. And as mentioned, we'll come back to that one later on. Now with the header in place, let's now continue with those two images we need to place on our page. I have these images placed here in two separate divs, since they don't contain any real content it's just for layout purposes, that is why I'm using a div here. One has an ID welcomeimage, the one on the right has the ID coffeeofthemonth. Now these are pretty easy to add to our page, the welcomeimage gets a float to the left, and the coffeeofthemonth image gets a float which places it at the right of the body. The next block that we need to layout was that welcome text. For now we'll make it in just one column, we'll add multi-column later. This was placed in a section with an ID welcometext, which also again had a particular header. In my CSS, I'm again using a selector based on ID, and I make sure that this section floats to the left. I'm also giving it a width of 70%. I then need some separate properties on the header, which was a child, a direct child even of that welcometext section. So I'm again using the child selector. The aside with the ID of events is pretty similar to lay out. I have the hash events selector to select the entire side and give it a float to the right. I use again a child selector to apply a different layout on the header. And then inside of that aside, there was also a ul, so an unordered list, with a couple of list items, and I'm again using a child selector to apply different properties on these. The section with the bestsellers is pretty easy to understand, I'm not going to spend time on it. The last thing I'm going to add to my layout is the footer. Notice that I don't have any ID or class applied on the footer, so we'll have to use the tag name again. Indeed, here in the CSS, I'm again using the tag selector, and I'm using a clear: both property on it. This will make sure that the footer will take up all the available space and doesn't allow any other elements on its left or its right. Let's now run the page. Notice that the site's layout has dramatically improved, we're already much closer to where we need to get. Here you see the bestsellers, and the footer at the bottom. All of this was done by just applying some simple CSS with some selectors that we've seen in the slides. I'm not going to take you to all the different pages, they are all pretty similar. I suggest you take a look at the code in the download. Let's go back to the slides for now. Adding a Little Bit of JavaScript In the last part of this second module, I'm going to spend a couple of minutes talking about adding JavaScript to our pages. Remember that JavaScript is part of HTML5 and many features we'll look at in this course are in fact nothing but JavaScript. So it's important to know about some of the basics we'll have to use later in the course. First of all, do not fear. Many developers are still afraid of JavaScript, certainly when they are coming, for example from .NET. JavaScript does many things differently, that is certainly true, but it's important to look at the language and its characteristics with an open mind. And yes, to put it simple, there's no way around JavaScript when learning HTML5. There are a couple of things which are very characteristic for the language. Perhaps the most interesting one is that it is a dynamic language. Probably this is something that many developers coming from typed languages such as C sharp, fear most. Being dynamic, basically means that most of the work is done at run time, whereas with static languages most of the work is done at compile time. Static languages therefore catch more errors at compile time. It is also a functional language, meaning that functions in JavaScript are very powerful. They are on the same level as variables and objects. JavaScript is also an object-oriented language, which is something that many people well don't know. Objects in JavaScript exist, they have properties and methods. JavaScript objects are more dynamic of nature however, and also JavaScript doesn't have classes, like C sharp for example. Most of what we will do with JavaScript is talking to the DOM, or the Document Object Model. A browser creates an in-memory representation of the HTML document, and this model it exposes as an hierarchical tree, the DOM. We can access the individual elements of the DOM using JavaScript, and manipulate them later on. Whatever change we make will be reflected automatically in the page in the browser. Most of our JavaScript code will be written against the window object. This object can be seen as an interface between our JavaScript code and the DOM. The window exposes the document property, which represents the root of the DOM. With the document property we get access to the individual elements on the page. You can think of the document giving us access to the HTML tag on the page. On the document, a number of interesting methods are available, getElementById, getElementysByName, getElementsByTagName and a new getElementsByClassName. Using these methods we can ask the document to search for an element based on the arguments we pass it. In the sample code here, we have an element called shoppingcart. Using the document.getElementById, passing in that ID shoppingcart, we get hold of that element in JavaScript code. Now once we have access to the element, we can change for example its style attributes. Before we go to a small demo, one last thing. Where should we place our JavaScript code? It's again possible to write the JavaScript code inline, as seen here in the first sample. While this will work, it's certainly not the best practice. It leads to unreadable and unmaintainable code and also requires that the code is downloaded every time. A second approach is using a script block on the page. While this doesn't clutter our markup code, it's still being downloaded with every load of the page. Therefore it's better, but not ideal. The third and best option is placing the code in a separate file. This file can then be referenced from the page using a script element. In the last demo of this module, we'll add some basic JavaScript to our pages. Much more JavaScript will be added in later modules. Demo: Making Our Page a Bit More Interactive The goal of this demo is actually making sure that you have the basic understanding of how to include JavaScript and how to select elements using JavaScript. We'll be using quite a lot of JavaScript that is included with HTML5 in the upcoming modules. So I'm going to be doing something very simple in this demo. I'm going to start by adding a folder named scripts which is typically the place where we'll place all our our JavaScript files. In this folder I'm going to add a new JavaScript file, and let's for now call this myscript. So next step is going to do something very simple, I'm going to select an element from script and then I'm going to display for example an alert. So first let's give an element an ID. Let's for example, take one of the Add to Cart buttons, let's take this one, I'm going to give it an ID, ID is myAddToCartButton. Now in my script I'm going to start with selection of this element. I'm going to use for that the document.getElementById and I'm going to pass it, the ID that I just gave to that button. It was myAddToCartButton. Now I'm going to make sure that whenever someone clicks on that button an alert is being displayed. So I'm going to use B.onClick, and I'm going to attach to that a function. And I said I'm going to simply display for now an alert, using the alert function, and then I pass in the message I want to show, "Your coffee was added to your cart". To make sure that my page knows about the script, I'm going to be using a script block referencing to the JavaScript file. This brings us to the question, where do I put that script block? Now the thing is, we need to make sure that the elements that we're referencing from the JavaScript are already available in the DOM. And we can actually be sure of that at the end of the page. So below the footer, I'm going to include a script block. In HTML5 I don't have to specify that this is actually JavaScript, it is a default, so I can just say that the source is myscript file inside the scripts folder. Let's now run this page. Now in the resulting site, we can actually see the script working. I can click on this Add to Cart button which doesn't really look as a button yet, and then the alert will be shown, which means that the document.getElementById found the actual element, attached the onClick so the script has been executed. This should give you a very basic understanding of JavaScript, how to find elements, and how to reference JavaScript files from our HTML pages. Let's go back to the slides for now. Summary We've reached the end of this second module. In this module we have seen how CSS can help us creating the visual part of our site. We'll see much more about CSS3 later, including that it is a very important building block of HTML5. We've also touched JavaScript briefly, covering just enough to make sure you'll be able to follow along with the following modules, where we'll be using the built-in JavaScript libraries quite a lot. So that's it for Module 2. I hope you have enjoyed it and I'm looking forward to seeing you again in Module 3. Thanks for watching. Navigation, Forms, and Validation Module Introduction Hi, and welcome to module three of this Pluralsight course named Practical HTML5. My name is Gill Cleeren. You can follow me on Twitter @gillcleeren. In the first two modules of this course, we have created the skeleton for our site. We have created some base pages already. We have also styled the pages somewhat with some basic CSS and we've thrown some simple JavaScript into the mix. In this third module, we are going to extend the site. That's quite logical. We're going to make some changes to the navigation of the site, as well as allow the users to place an order for coffee using a form. In this module we'll spend some time creating that form which uses all the new additions added to HTML5 which make it easy to manipulate user input. Let's start by taking a look at the agenda for this module. As mentioned we'll ask the navigation to decide. For this we'll use the nav element to indicate to the browser what is making up the navigation of our site. Secondly we are going to create a form for the checkout procedure for our site. HTML5 comes with a lot of new input types. And we'll use these to create a better experience than what was possible with HTML before. In the third part, we'll look at some other new options we have in HTML5 to validate user input. Again, with the purpose of making sure that the user gets the best experience while working with our site. When we will have reached the end of this module, we'll have created a menu inside a nav block clearly indicating what makes up the navigation for our site. We'll also have created the checkout page, on which we will use the new input elements that come with HTML5 out of the box. And not only are we going to use the new input elements, the page will use the new validation options, which come bundled with HTML5. So by the end of the module we'll have another functional page added to our site. Navigation with the nav Element Every site needs navigation and our Joe's coffee store site isn't an exception to this rule. In the previous modules, I have intentionally not added any navigation to the site's pages yet. So we'll do that now. Before we add navigation to the site, let's see what HTML5 is adding in this area. Typically a site has its navigation at the top of the page. Most commonly it's a series of links pointing to other pages. In HTML4, so before the days of HTML5, you would normally wrap the links to all other pages inside of a div. Inside that div the actual elements would then be list item elements, li elements. So children of a ul, an unordered list. Using CSS we can then apply styling to make these into real buttons to navigate to the actual pages of our site. The surrounding div would normally be attributed with a class or an ID so that we can apply a style onto it. Typically this style or ID would then be named something like nav or navigation. And you can see that here in the slide. Now with HTML5, things haven't changed that much. However, we now have a new element, the nav element. And inside nav element, we'll use the ul again with the li items. The nav element mostly has a semantic meaning again. It's used to indicate to the browser and to search engines that its contents is the actual navigation of the page. The nav element isn't adding any visual behavior. It's not a creating a typical menu for our page automatically. For that, we still have to use CSS like before. Also interesting to note is that the nav element defines no extra attributes, so there's not a lot of customization we can do on it. Most of the time, the nav element is used for navigation on the page. Sometimes, it is also used for navigation within a document. This could be, for example, for a table of contents for a long document or page. Let's go back to our site and let's now add navigation to the pages we have created in the first two modules of this course. Demo: Adding Navigation with the nav Element When we look at the current state of our page, there is one very important thing missing, and that is navigation. It's currently impossible to navigate to other pages. So, let's add navigation. As explained in the slides typically we'll add navigation by means of an ul elements with an unordered list with a couple of li elements. Of course you can use other solutions but I'm going to go with this solution for now. I'm going to put this ul inside of the header. At this point, it's basically unclear that this ul is going to be the navigation of our site. I'm going to change that by surrounding it with the new HTML5 nav element. As explained in the slides, this nav element doesn't make its contents into a menu. We still have to use CSS for this. I have a class prepared called backgroundgradient. So, what these nav now did was actually making clear that its contents is the navigation for our site. Let's take a look at the result. In resulting page we now see our navigation sitting here at the top of the page. It contains a couple of links which are inside of a solid brown background color. We'll change that later into a grey and has the name of the CSS class. Let's go back to the slides. Using the New Input Elements Now that we have navigation in our site, we can also navigate to the checkout page, soon. But on the checkout page the user has to enter a lot of data, such as his address, his birthdate, his email, and much much more. We've had the ability to post data in HTML for a long time through the form element. Inside the form element, we could then add input elements which allow the user to enter data and later send that data to the server. In previous versions of HTML, we were quite limited in the amount of input that we had, and therefore, often had to resort to external libraries such as J Grain to guide the user while he was entering data. In this part we'll see how HTML5 changed this, and we'll soon start the creation of the checkout page in the next demo. When entering data in a rep form, it's important that we guide the user while entering data. Making sure that the data is right from the first time takes away a lot of frustration. If the data is valid, the user won't be presented with errors, indicating that he made an error. He won't have to wait while the page is sending the data all over again. So as the developers of the page we should try to guide the user in entering valid data. Now what is valid data? On the client we don't know all the business rules so we can't check everything, that's for sure. But there are quite a lot of things we can already check. Is the date entered by the user in the correct format? Or at least a format we can use later on on the server site? Or for example, is an entered email address really an email address? Again, previously we had to use third party libraries to do these validations. The third block is validation on the form itself. For example, it has the user entered data in all the required fields. While all of these features were possible before, they weren't possible with just HTML. We had to use some external library to make the forms more user-friendly and more interactive. With HTML5, all of these requirements are covered out of the box. For example, HTML5 introduces many new input types which can make sure that the data entered by the user is of the correct type. Let's start by taking a look at these new input types. So I said, HTML5 has a lot of new input types. They are indeed input types, so to add them to a page, we are still using input and then at the type. It is for this type parameter that a lot of new options have been added to HTML5. Note that not all of these new input types add validation. Some are there just to make the input of data easier by, for example, only allowing the user to pick a value. On this line here, you can see a list of new HTML5 input types. We now have color, date, email, number, range, search, telephone number and URL for website addresses. In the next couple of slides, we'll take a look at some of these in a bit more detail. Dates are probably the defect standard where users of a site and through all kinds of, let's say, incorrect data. The major problem with dates, is of course that the dates can be entered in many formats, and depending on the region of the user, often has a different input format as well. Previously, when a user had to enter a date in our site, we'd call for the help of, for example, jQuery. The new input type equals date brings out-of-the-box support for a date picker in HTML5. Here on the site, we can see an input type date inside our form. It's rendered by the browser natively, as we can see at the bottom of the screen. So that means that it looks different, depending on the used browser. Input type email allows us, as developers, to create an input where the user can enter a string, and the input can validate automatically if the entered data is indeed a valid email address. Again, this would normally require us to use JavaScript. However, this new input type email is included in the HTML5 file framework, and it's therefore easier to use this one straight away, when the entered data is invalid. So, in other words, not a valid email address that the browser will indicate this. This is what you see in the screen shot. Again, the way that this is handled, is dependent on the browser. Another new input type is URL. The name really gives away for what this new input can be used, I think. Indeed, it can be used to validate and to enter data is indeed a valid URL. When this is not the case, again, the browser will indicate this. On this slide here, you can see how Internet Explorer and Chrome are handling this, visually then. A neat new input type is color. Probably, this isn't one you'll need that often, but when you do, you'll be happy it's included in the HTML5 framework. What this input type does, it will open a color picker from the system and allow the user to select a color. Selected color is then shown and can then be sent to the server when the form is posted. The last two ones we'll talk about before the demo have to do with numeric input. The first one is, well, numeric input. So an input which only accepts numbers. There are a lot of places where this comes in handy, such as a quantity field or a credit card number. In the sample code here, you can see that the input type has been set to number. At the bottom, we can see how Internet Explorer and Chrome render this input. Chrome renders up and down buttons to increase or decrease the value of the entered input. IE doesn't do this and therefore has no specific rendering for this type. The second one related to numeric input is the range type. But the user can enter again a number value. But the value has to be between a minimum and a maximum. Then we can use the range input. In the sample code, we can see that the min and max attributes have been set to 1 and 10, respectively. This means that the final value can only be between 1 and 10. This input type is rendered using a slider element, as you can see in the screenshots on the slide. Again, there's a slight difference between how browsers are rendering this element. Now that we have seen the new input types, we are going to create the checkout page in the demo. For the creation of this page, we'll use of course these new input types. Demo: Creating the Order Page In this and in the following demo, we are going to work on our checkout page. The checkout page is mainly going to be a form where the user can enter his or her personal data, and also some information about the order. At this point, the checkout page is pretty empty. Let's change that. Since I want to capture information about a user, the user has to be able to fill in some form fields. And all these form fields are going to be part of a form so that's the first thing I'm going to be adding here. So here's my form, I've given an id of mainform. And the method is going to be post, it's going to be posting the data to our server. Inside of the form, I'm going to start by adding a field set and I'm also giving you the clause, and I'm also specifying the legend which is a text which will be appearing at the top of the form. All of my four fields will be inside of this div here. Quite logically, one of the first thing I want to capture is the first name and the last name of the user. For this, I'm using some old school input type is text, so plain text inputs. At this point, there's really nothing special with these two inputs going on. The next thing I want to capture is the email. For this, I'm going to use a new input type is email. Automatically, as we'll see when we run this demo, my browser will validate that the entered data is indeed a valid email address. Next I'm going to be adding some more input type equal texts. At this point, I set their simple text inputs, but will come back to them in the next demo. So I have added an input for the street, for the number, for the zip code, for the city, for the country, and for the phone number. Users can also enter their URL, for example, for their blog. For that, I'm using the new input type equals URL. Again, the browser will validate that the entered value is indeed a valid URL. Finally, I'm also adding again a plain input type equals text to enter a remark. Is enough my format can get multiple field sets and I'm going to do that next. I'm going to add another field set to capture information about the order itself. Here's my second field set. It has a legend, your order. And in there I'm going to add some more input types. First, I'm going to query the user for his or her birth date. This is typically something that I want to capture as a date. So I use the new input type equals date. Also Joe's Coffee Store offers the option to wrap items as gifts and they allow the user to pick the color of the paper. Now asking user to enter a color value is very hard. That is why we are going to use the new input type is color to capture the color information. And the people at Joe's Coffee Store are quite festive. They also allow people to put a couple of bows on their gift. Now this is a number and that is why we used the input type as number to make sure that the entered value is indeed a number. Finally, to submit the form we need to enter a input type equals submit. And we're ready with the form. Let's run it now. Here we are now on the resulting page. And let's test those new input types. going to enter a value for first name and the last name. And I'm going to enter an invalid email address. I'm going to try submitting this now. Place order, and you can see, the browser will flag an error. Another thing to notice is, the browser support has mentioned for the input types. The requested delivery date was an input type equals date. And as you can see, Internet Explorer doesn't give us any way to make entering a date easier. And the same goes for the wrapping paper colors, so that input type equals color. And let's jump to Chrome. And as we can see Chrome is effectively showing us a date picker. Also for the input tab's color it has some UI And Chrome also has better support for this input type numeric. It shows this numeric up down buttons, as you can see working here. Now our form is not yet complete. For example the country, I can enter whatever value I want in there. There are some other things that we need to add. Let's go back to the slides and in the next demo, we'll improve on this checkout form. Validating Form Input with HTML5 Elements We have now seen that HTML5 has added quite a few new input tabs which try to guide the user to enter data from the very first time. Now HTML5 does go further and adds more features to form data validation. There are new attributes which have been added. Which we can use to validate that data was entered where it was required, or in the correct format. This basically extends what the new input types are doing. Also, there are also new validations possible on the form level itself. Let's take a look. We'll start by looking at the new attributes which were added to HTML5. And the first one we'll consider is the maxlength attribute. The maxlength is pretty easy to understand. When we add this onto an input, the input length will be limited to the max length value. And the sample code here, we see that the input max length is set to 20. When the user tries to enter the 21st character, this won't be possible, as this is prohibited by using that attribute. The pattern attribute is also an interesting one. It allows us to specify a regex, a regular expression. Which will be applied on the entered data. Only when there's a match with the pattern the input is considered correct. Since this is extensible, we can use just any regex we want. This one is pretty useful. If you want to validate a phone number, a social security number and so on, this one is your friend. At the bottom of the page on the screenshot here, we see that when there's no match, the browser will notify the user of this. HTML5 also comes with the required attribute. This attribute, unlike the pattern attribute, for example, requires no value. We just add it onto the input. When this attribute is added, you specify that the form shouldn't be possible to submit without user having entered a value for this input. Now, when the user does try to click on the submit button to submit the form basically, the empty required fields will be marked. Again, dependent on the browser. And you can see that here in the screenshot on the slides. We've already discussed the range input type. You'll probably remember that this input was rendered as a slider. As such, a slider brings with it that picking a specific value is hard or difficult. If you want to have numeric input between a minimum and a maximum, you can use the min and max attributes. Which you'll remember again from the range input. However here we are adding these attributes on numeric input. In this case, the browser will render this as a regular input. But we'll flag an error when the specified value is not between the minimum and the maximum values. A good user experience here does require that you specify these values somewhere on the form. Instead of letting user guess, of course. The placeholder attribute can be used to specify the value or text which will be displayed inside of the input, when the user hasn't entered a value yet. This is useful to give a hint on the expected input. For example, we can use these to specify that we are expecting the user's first name and last name in the form. As you can see here in the code and in the screenshot. Now by default a form will validate that the entered values in the inputs are in the correct format. And that for example required fields did receive a value. Only after that has taken place, the form can be submitted. However, there is a novalidate attribute on the form. In specifying this value, you are saying to the form that it can't submit without file validations on the fields. Now you may ask, why is this useful? One good reason to do so, is that you'll do all of your validation on the server side. Which you should do in any case by the way. In this case, you can then use the input guides, such as date and color. To make sure that the user enters as much information as possible in a correct form. And if something goes wrong, you do want to use it to be able to submit. And you as the developer then agree to handle everything on the server side. Next you have on the novalidate on the form level. We also have the formnovalidate. The novalidate is a form attribute. The formnovalidate is an input level attribute. We can use this attribute on the input type submit. Which will allow to submit the form without validations on the client triggering. Let us now return to the checkout page. We'll extend it with the newly learned validation features of HTML5. Demo: Adding Validation on the Form In the last demo of this module, we are going to improve our form. This is how we left our form in the previous demo. Now let's add some validation to our input types. Let us make sure that the users do not enter a very long first name, or last name. So for the first name, I'm going to add a max length of 30. For the last name, I'm going to limit the input to 50 characters. Again, using the max length property. We had a bit of a problem with the country input. Basically, the user can enter whatever value he wants, however, we want to make sure that the user enters a three-character country code. Now, we're going to use the pattern attribute for this. The value is a regex, so a regular expression, that says that we can enter only three letters. We also want to enforce that the user does fill in the required fields. We can do that using the required attribute. So for example, the first name is definitely required. So I'm going to say required="required". I'm going to do that also for the last name, for the email, for the street address, for the house number, for the zip code, for the city, also for the country, for the phone number, the blog is optional, and the remarks are also optional. You also want to make sure that the user doesn't go overboard in the number of bows he wants on his package of coffee. We previously had created this as an input type as numbers, so a numeric input. But, we want to make that the user doesn't ask for more than 10 bows. So, I'm going to use the min and max attribute here. I'm going to say you have to have about, but a maximum of bows is 10. The last thing I'm going to add is a placeholder. The placeholder gives the user some extra information about what he should be entering. So for example, in the first name field, I'm going to say, placeholder="Enter your first name". Now this is not really useful. For example, let's go back to that bow field. And in here, I can also use the placeholder and say, Enter a value between 1 and 10, to indicate to the user how many bows he can add on his gift wrapping. Let's take a look at the result and you're going to notice that it has some more placeholders in place. I'm not going to be typing all of these. So, here we have the first name, the last name, the email, and so on and so forth, showing the placeholder. Let's try entering a very long first name. As you see, this is now limited to 30 characters. For the country code, unlimited to three alpha numeric characters. So, if I would enter Belgium, and will then submit the form, I'm going to get an error here. If I enter B-E-L, then this error will be cleared. You'll also see that when I now submit the form, there are many more errors popping up, and that is because all these fields are required, including this numeric one at the bottom. Let us now return to the slides and take a quick look at the summary of this module. Summary We have reached the end of this module. Let's do a quick recap of what we have seen in this module. We started the module by looking at the nav element. As you hopefully remember, this is not an element which adds any visual, it's instead used to wrap our navigation elements. In other words, it again has a semantic meaning. We've done looked at all the new options we've received in HTML5 for entering data. We have seen the numerous new input types which we have now in HTML5, and we've also covered the other four validation options which are not possible. And that's it for this module. Thanks for watching, and I hope to see you again in module four. Adding Style and Layout with CSS3 Module Introduction Hi, and welcome to module four of this Pluralsight course named Practical HTML5. My name is Gill Cleeren and you can follow me on Twitter via @GillCleeren. So far in this course, we have created a number of pages. But they don't always look really good yet. If styled them with CSS a bit in module two, when we focus mostly on using CSS for the layout. In this fourth module, we're going to prompt back to CSS and mainly we are going to add quite a few style changes using the new options added in CSS3. Now, CSS3 has quite a few interesting additions, and again, these will make our lives as web developers easier. It contains many new things for which we needed to perform some weird tricks in the past, or maybe use an external library. We are going to start the module again in the usual way, by looking at the outline, that is. As we can see, the outline is pretty short. We're going to spend most of our time looking at what is new in CSS3, part of HTML5. Secondly, we are going to change our layout a bit, since CSS3 also has new features to perform page layout. By the end of this module, Joe's Coffee Store site will again look much better. We will also have better layout added in places. For example, some pages will use the new, multi-column layout, courtesy of CSS3. So, a better looking site by the end of the module, can't wait. Lets dive straight in. New Features in CSS3 As mentioned,we'll start the module by looking at the newly added features in CSS3. So before HTML5, they had access to CSS 2.1 which was quite powerful already. However CSS3 builds on this foundation and adds many new options. Before we look at these new features, let's spend a minute positioning CSS3. CSS3 is the latest version of CSS, and now is one of the three main building blocks of HTML5. It is thus part of the standard itself. CSS 2.1, to the previous version, was one large specification, a large monolithic block, split into a number of sections such as selectors or the box model. Apart from the many new features that we'll look at in just a minute, the biggest change is probably that CSS3 has been split up in several separate modules. And each of these modules have their own development path for the future, independent of other features. This effectively means that some parts will evolve quicker over time than others without having to wait for a full update of the platform. And CSS3 by the way is also fully backwards compatible. Now, what are these new features in CSS3 now? Sticking to the terminology of CSS3 modules, the list you see here is just listing the most important CSS3 modules. We'll spend time looking at these and adding their features to the site. Selectors have changed quite a lot. The box model is still there. There are many new things for backgrounds and borders. We can also do more interesting things with text right out of the box. We can apply transformations, both in 2D and 3D, and based on that, we can do animations. We can also now lay out text in multiple columns, and there are some other changes in the ui-pod as well. As mentioned, these are now all CSS3 modules. And the goal of splitting up CSS into modules is making it possible for different modules to evolve separately. From this slide here, you can find a smallest of the relevant modules that we are going to discuss. If you follow the link on the bottom of the page here, you'll find an up to date list of all the modules and their current state. As I start by looking at these features in detail and how we can put them to use in our application. Selectors We'll start our journey with a stop at selectors. We've already seen selectors in the second module of this course. Just to recapitulate, using selectors we can make a selection in the DOM of the page. And the selectors are used in CSS to apply a particular styles of all elements which match the selector. In CSS3 there are many new selector options available. If you've worked with jQuery before, you will recognize many of the selectors as well. The selectors we have in CSS3 are an extension of the available selectors we had in the previous version. Selectors are now also a separate module in CSS3, which means they can evolve separately over time. CSS3 brings, like I've already mentioned, a number of new selectors, and we can place those in three groups: attribute selectors, pseudo classes, and pseudo elements. We'll start with the attribute selectors. The first one we have here is the starts with selector. It is now possible to make a selection in the DOM on attributes, where we select all elements that have a value for that attribute, that starts with the value specified in the selector. Here in the sample, we are searching for all links. Which have an href value which starts with https. This can be useful to mark links to secure parts of our site differently. If there's a starts with selector, there must be an ends with selector as well. And that is indeed the case. Defined elements with the value which ends with a specified value we use the dollar sign. As you can see here in the sample code. Starts with, ends with, there must be a contains as well. If we replaced the dollar sign of the previous slide with a little star symbol, we are searching for all values which contain the requested value. Let's now turn our attention to pseudo classes. The first one we'll consider is the nth-child selector. With the selector we can match every element. Which is the nth-child of its parent no matter what the type is. We, of course, can specify the value of 40 n, which can be an absolute value, or formula, or a known value such as even or odd. Take a look at the sample here. First we have a number of paragraphs on our page. I want to highlight a couple of them with a color. In fact, I want to highlight the even ones. For that, I can use the nth-child selector. I specify the value as 2n which means two, four, six, and so on, will be highlighted. So I then specify that p:nth-child. And it's the value 2n. This will then search for all even paragraphs within the search complex, which is in this case the entire page. A variation is the nth-last-child selector. This is basically the same but it start counting from the last element. So in the sample here, I used the nth-last-child, and I pass in two. What this will then do, is get in all paragraphs. Encountered to, starting from the last one and that one gets highlighted here. Another variation is the nth of type selector. It's quite similar nth child selector, but this one will only select items of a particular type within the parent. Take again a look at the sample here. If we include an anchor tag in between, that one won't be taken into consideration, since we are only interested in paragraphs for the selection. You must be thinking now, we can select even elements, last child elements, but what about the very first child? Well, I've got good news for you, that's also covered. Here we see the first of type selector, which will search for the first paragraph of its parent. And then, set its background. Another new selector, and I know it's all very simple, is the last child selector. Using the last child selector, we can select an element with is the last child of its parent. Here in the sample and selecting the last paragraph within its parent. There's also and only-child selector. Now with this selector we can specify a style for all elements which are the only child of their parents. So in the sample here. We now have two divs. I want to select only the paragraph which is the only child of its parent. And that is the case for the first one. The :not selector is also an interesting one. It allows us to basically invert a selection. All elements which are not a value in the selector will be part of the selection. Here in the sample, I'm selecting all elements which are not a paragraph using the :not selector and am making them blue. Now it's impossible to look at all available selectors we now have in CSS3. This last one is one I thought you needed to see, the out of range selector. Using this selector, we can select all inputs which have received a value which has not redeemed their specified range. That's a very cool one. And like I said, the list of other selectors we haven't covered is still quite long. On this slide I've listed some more that you can take a look at. Borders and Backgrounds Now that we have seen the selectors in action, let's put our attention to another new feature in CSS3, borders and backgrounds. Traditionally, borders on, for example, div elements were not possible to create without the help of something not pure HTML. We had to resort to JavaScript, use prefixes in CSS, or perhaps the easiest one of them all, we could use images. While all of these were okay, there's now better support for working with borders straight out of the box. CSS3 brings native support for rounded corners on elements. With the built in border radius property, we can specify that we want the corners of an element to be rounded. And for this, we can specify the radius. In the sample you see here, you can see the border radius property being used. And the result is shown for the div in the image. Next to borders, CSS3 also brings new options for backgrounds. The new background size property gives us control over how large the background image used, for example in a div or the body, should be. Here in the sample we are specifying that the image should not stretch. Instead, it should be sized to 300 by 100 pixels. Using the background size, we can also define an image to stretch to fill the entire background of the element it's being used for. Here we see the background size set to 100% in both directions. So the image will stretch to fill the div. CSS3 also gives us control over where the image should position itself within its container. We can do this using the background-orgin property. Here, in the first image, you see that the background image is aligning entirely on the left border of the div. The background origin here has been set to border-box. In the CSS box model, the border is surrounding the container. So that is why you see the image touching the left border of the div. The image in the second div is set to content box, so the image aligns with the actual content container. Finally, to finish this short discussion on borders and backgrounds. CSS3 also offers the ability to specify on more than one background image in one container. Here in the sample we have defined multiple images in a comma separated list. The images will be stacked on top of each other, where the first defined is the lowest in the stack. Gradients The next addition to CSS3 we'll consider is Gradients. Gradients are built in and allow us to create color flows from one color to another inside elements. CSS3 has support for linear and radiant gradients. Using gradients from code, we can avoid downloading some images, and let the browser do the drawing of the gradient. Let's take a quick look of how we can use these gradients. In the first sample here, we see the most basic linear gradient being used. I have a div and in the CSS for this element, I specified the background to be linear gradient. To do this, I specify a linear gradient? And then the colors I want my gradient to contain. The result is a gradient from top to bottom which is the default. As you can see in the image shown on the slides. If you want to have a horizontal gradient we can use a extra parameter as shown here. Notice that to right was added. The gradient is now going from left to right. And of course, it's also possible to make the gradient flow in a diagonal direction. And the sample here, I want my gradient to go from the top left to the bottom right. And in the code, the parameter is now set to bottom right. And next to linear gradients, we can also use radial gradients. In the first sample here, we are now using the radial gradient. Again, specifying the colors we want to use. By default, the colors will be spread equally. The first one being the center of the gradient, so here yellow is at the center. If you want the colors to have a different weight. In other words, if the gradient itself should not be spread linearly, then we can specify this as shown on the slides. The yellow part should be pretty small, only 10%. Whereas the red part should be 60%. The image shows indeed that red is now much more present in the gradient. Transforms We have a couple more topics to see before we apply all this knowledge in the demo. Hang in there. The next problem we'll tackle is transforms and animations in CSS3 and we'll start with transforms. Now what are transformations? Let's cover that first. A transformation allows us to alter properties of an element to change its visual representation. In CSS3. We get support for 2D and 3D transformations. We'll only look at 2D transformations in this course. The available transforms allow me to change the size, the shape, and the position of an element. Previously, it was only possible to do these type of things with plug-ins. Now it is built-in again with CSS3. So in a bit more detail, what transforms are supported in CSS3, then? We can do a translate, which is probably the easiest one. A translate just gives an element a different position. It translates the position. A rotation will, quite logically, apply a rotation on an element. A scale transform allows us to make an element smaller or larger, whereas a skew transform allows us to turn an element in a different angle. A matrix transform allows us to combine multiple transforms in one. Let's take a quick look at some of these transforms with a small sample. In the code here, we have two disks in which we apply a CSS style. The first one, is the one that you see at the top of the resulting image. The second one got an id rotate. And we have also a second style, div rotate. And in that style we use the new CSS transform property and reapply a rotate transform. As value we specify the angle we want to rotate and here it is 45 degrees. The second sample here shows a similar example, but now instead we have a skew transform being applied. Notice that there is still a rotation, but the element is skewed. So it's stretched by pulling its corners. In the code, we have used the skew transform, as you can see highlighted here on the slide. With CSS3, it now becomes possible as well to embed simple animations directly in CSS. I should emphasize that simple aspect here. For really complex moving stuff, you should look at, for example, the canvas. If you think of animations, what are they really? An animation is the change of a value of a property over time. CSS animations allow us to basically go from one style to another over time, thus changing the value of a property. The CSS3 animations are built into the platform, so there is, again, no need to use plug-ins or even JavaScript to use them. Let's take a quick look at animations. How do we work with these animations then? We start with the creation of an animation using the @keyframes rule. In this rule we specify the animation. In the sample code you see here on the slide, we see that there are different CSS rules defined for the different times in the animation. These different times are shown using a different percentage value. So what this code says is that 0% of the animation the background should be green at 25% it should be brown and so on. 0% is of course the beginning, 100% is when the animation is complete. Now we have just defined animation, we need to apply it on an element so that that element gets animated. Here on the slide you see the animation again and there's also a style defined for this. And in this stop, a new property is being used, the animation property. Using this value, we then point to the animation. In this case, homeAnimation. The second parameter of your 10s so the 10 second one defines that the animation should take 10 seconds. As mentioned, animations are quite an extended topic, and they will take us too far. Therefore this slide has some other properties we can use in combination with CSS3 animations. Most of these are pretty easy to understand. For example, the animation-duration, allows us to specify how long an animation can run. Text Effects The last thing we'll take a look at before we go to the demo is text effects in CSS3. Text effects are a very small new feature, however I think in terms of what we can do with them, they might be one of the most important ones. The first thing related to text is the ability to apply text shadows on text. And unlike I mentioned, this is a small feature but since it is now done by the browser for us, it relieves us from having to download images for a shadowed text. in the sample here, we see a style for header one being defined. I'm using the new text shadow property, as values we specified are horizontal and vertical shadow. The third parameter allows us to define the blur distance, so an offset, and the fourth parameter allows us to define the shadow color. And you can see the result here on the slide. One of my favorite features is the built-in support for using custom forms. We can, using CSS3, show text in a font we include in the page. No longer are we limited to just using system fonts. We can use just about every font, like TTF, OTF and other file types. How does this magical trick work then? We have a new CSS rule, @font-face. In there, we specify the source for the font file using a URL notation. We also specify a name for the font family, which is how we refer to this font. We can then use this font in a WOFF style as is the case here for the div. In there we set the font family to the font family defined in the @font-face rule. As you can see in the image, we are using a custom font for the text. We have covered a lot of ground already, so let's now go back to Joe's Coffee Store and apply all this knowledge in the next demo. Demo: Using CSS3 to Make Our Site Look Better! In the first demo of this module we are going to add some new CSS3 features to our site. So what you see here is the current state of the site. We still have the plain old font for the header. We also have a plain color here as the background for the navigation menu. And we also have this Add to Cart as plain text, and it should actually be a button with rounded corners, perhaps. Let's go to Visual Studio and make some changes in the code. So here in the index we have the navigation and that has a class backgroundgradient. Remember that the nav element is just a structural element and it behaves more like or less like div, so we can actually apply a background color onto it and in this case that will be a gradient. I've already named this class backgroundgradient, as we saw before. Let's take a look at the CSS. So here we have the background gradient CSS class. And we have a plain color set as the background for that nav element. So we're going to change that. Now for this I'm going to use the new linear-gradient, which is part of CSS3. So as you can see, the background now is set to be a linear-gradient, which goes from left to right. This is the starting color, and this is the end color. Let's take a look at this in the browser and as you can now see, the color is going from a lighter brown to a darker brown here on the right, and I've used the same clause a couple of times throughout my page. The next thing I'm going to add are round corners for the Add to Cart buttons. For this I'm going to add the add to cart button CSS rule. In this addtocart button CSS rule, you can see that I'm using the new border radius and I set that to eight pixels. Let's take a look at this in the browser. And when I scroll down, we see neat that the buttons have a round corner which I've done just using plain CSS. Next, I'm going to change the font that my header is using. Normally, I would have used an image to do so. Now, I can use just any font that I want to embed with my page. What I'm going to do for this is, first create an at font face rule. We're going to use new addfontface. In my forms folder, I have this lobster 1.3.otf, which is a font file and that's the one I'm going to be using. So I'm going to set the font family to header funct. This is the name that I'll be using for my font when I want to apply it on a particular element. Next, I'm going to point my CSS. Do that from file in my functs directory. So we're going to use the source. And I'm going to set that to the URL and that URL is in the phone's directory. Use my lobster 1.3 OTF. So now, we created my font phase and I'm going to apply it. So let's search for header name. Which is the CSS rule which is applied on the text in header. And I'm going to set the font family to what we just used, and that was header font. Let's run this. And as you can now see, the Joe's Coffee Store header is now in a different font without using an image for this. Now while we're at it, I'm going to also apply a shadow on my text in the header. And for this, I'm going to use the new text-shadow property. And I'm going to give it a couple of values. Let's take a look at this in the browser again. As you can now see, Joe's Coffee Store now has a shadow adding the effect of depth. The last thing that I'm going to show you is how you can do a transform in CSS3, and I'm going to do this by, for example, rotating the footer slightly on the page. So, let's go and search for the footer. And on this footer, I'm going to say that it has to a transform. And the transform is going to be a rotate over let's say, for example, ten degrees. Let's run this again. And as you can see, the footer has been rotated over the rest of the content, which is of course not what you want, but you see how a transformation can be used. Let's go back to the slides for now. Page Layout: Multi-column Support In terms of CSS3 and what is new in this area, we've covered most already in this chapter. In the last part, we'll be looking at multi-column support. Imagine you have a large chunk of text on the page, perhaps a product description or an article. If you create your site layout to the bulk of the text is in a stretching div, the lines of text will become very wide. Now, this wasn't really a problem in the days of smaller screens. This has changed today quite a lot. Text, which is in a very wide area becomes hard to read. Because the user probably has to turn his head from one side to another to simply read the text. A solution is, of course, dividing the text in multiple columns and CSS3 has a solution for this on board. Take a look at the sample here. Notice that we have a style and inside the style, the column-count property is set to 3. I am going to now apply this style on a div, the content of that div will be divided in 3 equal columns, as you can see in the screen shot. So effectively, this type of multi-column simply divides the available space in tree. This type of layout is similar to a magazine layout, so this will definitely help readability. Alternatively, it is also possible to specify how wide a column should be. For this, we can use new column-width property, as we can see on this line here. Based on the available space, a number of columns will be created. Therefore, we can end up with just one column, or a large number of columns. Another property we can use in this area is the column gap. And using this property, we can control how wide the separator between two columns should be. Of course, this has an influence on the width of the columns. Let us now add support for multi column in our site. Demo: Adding Multi-column to the Detail Page In this very short demo, I'm going to show you how you can work with multiple columns of text. We have decided, together with Joe's Coffee Store, that the welcome text on this landing page, is easier to read when we divide it over several columns, and we can use CSS3 for that. Let's take a look. What we're going to do is, we're going to use this new welcome text section and use the colon count and related properties on it. Let's go to the CSS and search for welcome text. And in the welcome text, I'm going to specify that column-count is going to be set to two, and for all the browser support, I'm also going to set the webkit-column-count to 2. Let's run this again. What you see now is that indeed, the content has been divided over two columns. Alternatively, I could also have used the column width. And set this to 200. And also specify the column gap, which is the spacing between different columns. I'm going to set that to, for example, 40 pixels. Let's see what this looks like. I think I now see, the content has been divided over three columns, each with a width of 200 pixels, and the gap between them is 40 pixels. Summary With that, we have reached the end of this module. You've seen quite a lot of interesting new features in CSS 3. We started by discussing how CSS 3 is an evolution of CSS 2.1. And we saw that CSS3 is now divided in separate modules which makes evolution easier. As a technology, the main message with CSS3 is that it makes things easier for which he had to use either some dirty tricks or another language or technology in the past. With CSS3, many things are now included straight out of the box. And that's it for this module. In the next module, we'll look at the canvas and media, and I hope to see you there as well. Thanks for watching. Adding Functionality Using Built-in JavaScript Libraries Module Introduction Hi and welcome to Module 5 of this Pluralsight course named Practical HTML5. In the previous module, we have spent time making sure that our site looks a lot better using the new features added in CSS3. But as you'll hopefully remember HTML5 is a collection of changes made to HTML, CSS, and JavaScript. And in this module we are going to focus on the latter. We're going to add functionality to allow the user to drag content, store content locally on the device, and figure out the location of the user. For this you are going to use again some built-in libraries which come together with the HTML5 standard. And we'll start by taking a look at the outline for this module. We're going to start this module by adding functionality for the shopping cart. Instead of using regular buttons to add a product to the shopping cart we're going to allow the user to drag a product to the shopping cart. For this we'll use the newly added drag and drop API. Secondly, we are going to extend the shopping cart so we can save the contents on the local device. Previously, we were pretty limited in what we could store locally. We are going to make use of the new storage options to store cart contents. Finally, we are going to figure out where the user is physically using the geolocation API. Also part of the HTML5 standard. So after finishing this module, our web application will be even more functional. We'll have added the ability to drag products to the shopping cart. When the user logs off it doesn't lose the contents of the cart. Instead we'll have it saved locally on the system. Finally, the user will also be able to figure out how to drive to the physical Joe's Coffee Store. Since we find his current location using the new geolocation API. Lots of cool stuff, I think. Let's get started. Drag and Drop API We're going to start by adding functionality to allow the users to actually buy coffee in Joe's Coffee Store. We so far have created the pages where the user can see the different types of coffee. But we haven't added any functionality to allow adding products to the basket. We're going to do that first. To add this functionality, we're going to allow the user to drag items from the product list to the shopping cart or the basket. And that functionality can be added with a new, built-in API, the drag and drop API. I assume you're familiar with the concept of drag and drop. It's an interaction most computer and tablet users are familiar with. It's definitely an indirection which originated in desktop applications and you now also see it's commonly being used in websites. Mail sites such as Gmail or Outlook.com, have for years allowed the user to pick up an email and drop it in a particular folder. Just like many things we already covered, drag and drop wasn't possible before without the help of an external library. For the purpose of drag and drop very commonly jQuery was used. Of course, other alternatives were also possible. With the introduction of HTML5 we now have out of the box support for this way of interacting with content. Drag and drop is part of the native HTML5 implementation and is therefore widely supported in modern browsers. The API is pretty straightforward, and is based on the system of events, a couple of new attributes. We add on the elements and the dataTransfer object. Before we add drag and drop to our site, let's start by taking a look at how these new items work in the next couple of slides. I will start with new attributes. There are two new attributes we can add on elements on our pages. The first one, draggable, is used to mark an element as a possible draggable element. An element becomes draggable when we specify the value of draggable to be true. Being draggable means that the browser will allow to use it to perform a drag operation with that element. We can use this attribute on just about all elements. It's not limited to a particular type of element. If we set the value to auto, the browser will use its default implementation. One thing to note here, is that most browsers make some elements draggable by default. This includes images, text selections, and a couple more. The second attribute is the dropzone attribute. While you'd think you need this to mark an element as a place to allow dropping other elements, you're actually wrong. It is not needed for implementing drag and drop. Effect at the time of the creation of this course this attribute is not supported in any major browser. So we won't spend any time looking at it. Next are the new attributes, we also get with the API a number of new events. And we to wire up these events to actually implement the drag and drop operation. We'll add these events in the upcoming demo, but let's take a quick look at them now already. Typically, once we have an element which can be dragged, we start the drag operation with the dragstart event. In this method, we'll typically apply a style on the dragged elements to indicate we are actually dragging them. Secondly, we can add support for the dragenter, dragover and dragleave events. These again mostly events we can use to give a visual indication about where the user is dragging an element. For example, we can make sure that an element lights up when it is over a drop zone. To complete the drag operation, we also need to add support for the drop and the drag and events. And in these events, we first need to make sure that we prevent the browser from performing its default action. Which is redirecting the user to another page. We can do so by calling the preventDefault method, as you can see in the sample code. If you would use only the attributes and events, we still wouldn't end up with a working drag and drop operation. There's a current building block and that is the dataTransfer object. It's actually the workhorse of the drag and drop operation. Since it can be use set the data to drag in the dragStart and make that data available in the drop event. In the sample code we see here. You can already see that we are using a number of properties and methods of this object in the handler function for the dragStart. In a drop handler, we are using the data transfer object to get the data which was dragged. The dataTransfer object exposes a number of properties and methods like I just mentioned. The dropEffect property is a property which is used to specify what will be the type of drag and drop operation. Along with this, it will also define which cursor will be shown while we are dragging the content. The value of this property should always be a value of the effect allowed enumeration, which can be copy, move. Linked or none. It's possible to drag a list of files as well. These are set in the file property, and the types property can be used to store a list of former types, of the data, which is told in the dataTransfer objects. Next to properties, we also have a number of methods on the data transfer object. Using the setData, we can indicate data we want to put in the data transfer object. So what will be the data we're dragging basically. When using the set data, we need to specify the format, which is the mimetype. And then in data, the actual data. Using the getData, we can well, get the data for a given type. Using the clearData, we can remove the data for a given type or delete all data at once if we do not specify a type. The setDragImage method can be used to set another image to be shown during the drag. And you see that here in a sample code. The addElement finally is used to specify the drag source which defaults to the element being dragged. In this demo, we are going to use the drag and drop API in our site. Demo: Drag and Drop API In this demo, we are going to add support for drag and drop in the shopping cart. I'm going to do that by using the new drag and drop API, which is of course a JavaScript-based API. I'm going to start by adding a new script file in my scripts folder. And I'm going to call that drag and drop. In the All Coffees page which is the page I'm going to use, I'm going to add a reference to this file. And in Visual Studio, I can simply do that by dragging that script file into my head. Now we're going to have to create some JavaScript. going to start by opening my JavaScript file and I'm going to start by adding a function called addDragAndDrop handlers. This doesn't receive and parameters. There we go. So I'm not going to be doing all the typing because it's quite a lot of code and its very error prone when typing. So I'm going to do some copy/pasting of some snippets. The end result that we're going to be working towards is that the user can pick up the image of the coffee in the All Coffees page and drag that on to the shopping cart, and that will then add that coffee to the shopping cart. First, I am getting hold of all the coffee images, by doing a document.get ElementByClass name. Pallet article wide, which the actual images of coffees. Next I often need a reference to the shopping cart. And we're going to call that shoppingCartDropzone using the document.getElementById passing in shopping cart, which is a div on which I can drop my coffee images. Now, inside that shopping cart, I have a ul and I'm going to get hold of the ul by using document query selector all, passing in a selector. Shopping cart space ul. So the child of shopping cart of type ul. Now that I have all the elements I want to work with I'm going to add some functionality. What I'm going to do next is make sure that each image in the coffee images area here, listens for being dragged. So I'm going to add a full loop that loops through the coffee images and on each coffee image I'm going to attach using the addEventListener, a listener to listen for the drags con event. And whenever that drags con event fires, this function is going to execute. In here I get hold of the data transfer object and I'm going to say that I'm going to do a copy and very importantly, I'm also going to set data onto the data transfer object. This is the key text, and the data is the id of the coffee image I'm dragging. This is very important, because this way when I drop the image, I'm actually going to know which image was selected. I'm also going to attach an event onto the shoppingCartDropzone, the div, that is. And I'm going to use the drag over and I'm going to say that if there is a default event being fired, cancel that, prevent it from happening. I'm also going to say that the drop effect should be copy. And now I'm going to implement the actual dropping of an image. So again on the shoppingCartDropzone, I'm going to also attach another even listener, in this case for the drop event. And so this function will then execute whenever I drop something onto my div. The first thing I do here, is from the data transfer object, I'm going to try to fetch the data that is associated with the key text. Which was in this case an id for an element. So I'm going to get hold of that element by searching the DOM for that element, using the getElementById, passing in this coffee id. At this point my page basically knows which element was dragged and dropped, but there's no visual feedback, so I'll have to do that myself. And for this I'm going to write the add coffee to shopping cart function in just a second, passing in the element as well as the coffee id. Let's add that function. Now in this function, I'm going to start by creating a string, HTML. And the string is composed out of the id, space, and then from the items, or the actual element, I'm going to try to fetch the price, which is currently in the data dash price attribute. Then I am going to create a new li element, so a list item element. And I am going to set it's HTML, so using the error HTML property, to my created HTML. And finally I am going to append that li using append chart function, onto the shopping cart, which was actually the ul that I grabbed earlier. At this point, my script is ready. Let us now call it from the All Coffees page. So here at the bottom, I'm going to use the document.addEventListener again, that says when the DOM is loaded. Call my addDandD handlers function. Let's run this. So at this point the shopping cart is empty, I click on an image and I start dragging it. It cannot be dropped here, but as you see, when I drag over the shopping cart, the pointer is changing into that copy handle. And I drop it, and automatically, the coffee is added to my shopping cart. At this point, though, when I refresh the page, this is gone again. In the next demo, we'll fix that. Web Storage Options We have now made it possible to create our cart using drag and drop. In most web apps, the cart is immediately stored on the server using a server side technology such as asp net mvc. Since that is not the focus of this course, we are going to take a slightly different approach. We are going to store the cart locally. This way when the user leaves the site and later on returns, the contents of the cart isn't gone and he can continue shopping. And for this we'll use another new feature in HTML5, web storage. Before we look at web storage, let's take a look at what we used to have in terms of client side storage options before HTML5. Well the story is quite thin. The only option we had in HTML was cookies. I assume most of you are familiar with the concept of the small text-based files which are stored by your browser on the local disk. And since they are plain text and are stored in plain sight on the local disk, they're not secure. So it's out of the question to put any sensitive data in there. The size is also quite limited. A cookie cannot be larger than 4 kilobytes. And per domain, we are limited to 20 cookies. On top of that, with all the recent privacy issues, many people turn cookies off. Which will then cripple your site experience. In all, cookies were an okay solution in the 90s. But the world has evolved. We have other needs now. So what do we need in terms of storage for building greater replications then? We definitely need more space. A limit of 4 k is not going to cut it. We also need the option of real storage on the client. What I mean by that, is that we are in need of more capable data storage alternatives, and ways to work with the stored data. Also, the data should be persistent on the client. And should certainly not be deleted when the user closes the browser. And unlike cookies, the data should not be sent over the wire with every request. As you can see, the needs are very different from what cookies can offer us. With HTML5, another new API is introduced, namely web storage. Also referred to as local storage or DOM storage. As the name implies, web storage will allow our web applications to store data on the client in a persistent way. And in a much better way than what we could achieve with just using cookies. Firstly, web storage has an API, meaning that we have methods to add and remove data. This already fulfills the requirement to have real data storage from the browser. The data is stored in key value pairs, which we can query. The storage is entirely local, so the data is local on the device and remains there. This also means the data isn't being transferred with every request. A local storage object can be created per domain, which is somewhat similar to what we had with cookies. A local storage is supported in almost the same way in major browsers. Most browsers give us five megabytes per domain for local storage. Some browsers give us ten, but there seems to be a consensus around five megabytes. Web storage is implemented in two different objects, local storage and session storage. Now, what is the difference between these two? Data stored in local storage is persistent, even after closing the browser. It is not tied to just one tab or browser window. It is shared between tabs and browser windows. One instance of localStorage is created per domain. sessionStorage on the other hand, will be deleted after closing the browser window, or tab. So the storage is local. But only persistent as long as the user keeps the window or tab open. It is thus more temporary of nature. Also a session storage instance is linked to a tab or browser window. If you have multiple tabs open with the same site loaded inside, each tab or window will have its own instance of session storage. Let's see how we can work with web storage. As mentioned, it's a JavaScript API, so we can only interact with both the session and localStorage through code. And the code you see here, we are first checking if the storage is supported by the current browser. We do so by checking if the browser recognizes the storage object. If that is the case, we are using the local JavaScript object. And using it's setItem method to store a value locally using a key, in this case, the word coffee. Afterwards, we are retrieving the value by invoking the getItem method on the local storage object. Now, what else is supported in the API for web storage? Notice that the API is the same for both local storage and session storage. We have the setItem and getItem methods which we already saw being used in a previous slide. There's also a removeItem which accepts a key and will then remove the item from storage if found. The clear method will clear all the stored items, and using the length property we can see how many items have been stored already. The storage object also supports an event called storage. This event will be fired when data is being changed. We can register for this event to be notified about changes being made to the local or session storage. In the sample code you see here we are attaching a call back named logMyStorageEvents to the storage event. The parameter is of type storage event and exposes a number of interesting properties. Key contains the changed key, old value contains the value being replaced with the new value. In the following demo, we are going to save the comments of the quality locally using the local storage options we just saw. Demo: Web Storage Options The previous demo is finished with the shopping cart supporting drag and drop. But saw that on refresh, the entire shopping cart contents was gone. We're going to fix that by adding support for your local storage, also in the shopping cart. We're going to continue working with that same JavaScript file, so remember that we had the addDnDHandlers function. The first thing I'm going to do is I'm going to create a constructor function for the cart object. And inside the cart, I'm going to create basically, an array for the coffee's property. Which is going to contain all the coffees which were added using drag and drop. And I'm going to persist those using local storage. Next, I'm also going to create a coffee object. Again, using a constructor in JavaScript. There we go. So now I have a coffee which has two properties, coffeeId and price. This doesn't do anything yet, we're going to use that in just a second. Next, I'm going to create a variable currentCart. I'm going to set that to null for now. Now this currentCart is going to contain the actual shopping cart's contents that is coming from localStorage. First, I'm going to check if I already have something stored in localStorage for this page. What I'm going to do is I'm going to ask localStorage to check if we have an ItemWithID cart. I'm going to try to pause that and I'm going to store the result in currentCart. And if currentCart doesn't exist yet, I'm going to initialize an empty cart with a function called createEmptyCart. And let's first create that function, createEmptyCart. going to put it here at the bottom. I'm going to, most importantly, create in my localStorage, an ItemWithID cart. And I'm going to set that to the stringification, the JSON stringification basically of that new cart object that I just created. Then, I'm going to set currentCart. Our arrival currentCart to the parsing of the cart item that I'm getting from localStorage At this point, I either have an already existing shopping cart in local storage, or I have an empty, just initialized shopping cart, as well. Next, I'm going to synchronize my UI. And I'm going to do that with a function called updateShoppingCartUI. going to call that function. Now I of course have to implement that function. Let's put it again here at the bottom. What I'm going to do in this function is, first set the inner HTML of my shopping cart, so that was my div ul, to empty. For each item, or each coffee, basically, that I can find in the area inside my current cart object, I'm going to execute this JavaScript. I'm going to, again, initialize an li. I'm going to set its inner HTML. And I'm going to append it to the shopping cart, which was that ul. That's basically what we already did earlier. So now my shopping cart is basically in sync with the contents of the local storage. Now, I also have to make sure that when somebody drops a coffee onto my shopping cart, it gets added to my local storage. To support this, I'm going to add onto my currentCart a function named addCoffee. And inside this function, I'm going to add the coffee to the array of coffees. And also, I'm going to overwrite what is currently stored in localStorage with id cart with the stringification of currentCart. Now, this function is now created, but it doesn't get called yet. When do I have to call it? When somebody drops a coffee onto the shopping cart. In the drop, we had the call to this addCoffeeToShoppingCart. I'm going to change that function. going to remove the current contents. This is now the new functionality. First, I'm going to get hold of the data-price attribute again. And I'm going to store that in a variable price. I'm also going to create a new Coffee instance, passing in the id as well as that price. Then, I'm going to call my addCoffee function, passing in that function. And if we look back at what this did, this will add the coffee to the array, and also overwrite localStorage. So now we have safely stored my data in localStorage. And finally, I'm also going to update the UI to reflect the change. If everything goes well, we should now be able to see that upon refresh your shopping cart remains intact. Let's run it. Let's go to our coffees page. I'm going to add a coffee here, and one more. I'm going to refresh the page. And as you can see, the shopping cart now stays intact. I've saved it locally, so upon return to my page, the coffees will still be in the shopping cart. And this of course greatly improves the shopping experience for the customer. Let's go back to the slides. Geolocation In the last part of this module, we are going to make use of one more API in our site, the geolocation API. The scenario is that we want to show users the route to the physical store from his current location. Now, to find that current location, we'll use the geolocation API built into HTML5. The concept of geolocation is very commonly used nowadays. With devices in our pockets which are constantly connected, we aren't difficult to trace. All these devices and also modern laptops have the ability to figure out where we are through GPS, Wi-Fi, or cellphone triangulation. When a device has this capability, it's only a small step for the browser to be able to get this information as well. And when the browser can access this information, this opens up a lot of interesting scenarios for many sites. The retrieved geographical position is normally very accurate. Maybe you've already used Google Maps or some other mapping service, and these services automatically zoom in on your current position. So the browser has in that case done a good job finding your current latitude and longitude. Sometimes the information can also contain information about speed, height, and heading. Many sites love to know where you are currently. This gives them the ability to serve you better. Sites with weather information, traffic information, or maps, for example, all benefit from this information. On the other hand, geographical information is sensitive data. And as a user, you don't always want each site to know where you're currently at. Therefore, whenever a site wants to access this information, the browser will protect you as a user, and give you a warning, like you see here at the bottom of this slide. This is simply a screenshot of Internet Explorer, other browsers are doing something similar. In the warning, the name of the site is displayed. This is important so that the user knows if it's the main site or perhaps a banner hosting site which is requesting this information. There is no way for your code to bypass the appearance of this message, which is good news for the user. The user, therefore, remains in control, and depending on the browser, has the option to hide the information once or always for that particular site. Let's take a look at how the geolocation API works, then. The API is available through the window.navigator.geolocation object from our JavaScript code. The most obvious thing that we want to do with this API is asking for the current position, which we can do using the getCurrentPosition method. In the sample code here, you're first checking if there's support for geolocation. And if so, we are using the getCurrentPosition method. In the showPosition, so the success callback, we get a position object, which allows us to retrieve the latitude and the longitude. More on the latter in just a second. Next to the getCurrentPosition method, we can also use the watchPosition method. In the sample you see here, we see how we can use the watchPosition. We get the currentPosition, and we'll get in a new value whenever user is moving. This is useful when we're interested in updates about the location of the user. When we are no longer interested in receiving updates, we can stop the watch using the clearWatch method. When we want to figure out a user's location, we can use the getCurrentPosition or watchPosition. There is, however, an extra parameter we can pass into both methods. This object is the position options object. And it allows us to configure the way that the geopositioning is done. The object defines a number of properties. The time out is pretty logical. It says when a new value needs to be retrieved the enable high accuracy allows us to specify how accurate the position needs to be. In other words, if the browser must try to use the GPS, if available. Setting this to true will also mean that the position retrieval will take longer. And finally, the maximum h specifies how old a cache position can be for it to be still accepted. In the sample, we also see how the position's object is passed to the watch position method. We've already discussed the success in error call back, but we haven't looked at the position object returned to us in the success call back. This object exposes the coordinates property, which exposes a number of properties, which contain all of the values. For the position information. This object exposes the coordinates property which exposes a number of properties which contain all the values for the position information. Note that not all values will be filled in all the time. It depends on the device and the situation, of course. We can find this way the latitude, the longitude, the altitude, the accuracy, the speed, and the heading. In the error callback on the other hand, we'll get information about what went wrong. In this case, we're getting in a position error object. Based on what happened while trying to retrieve the position information, a different error code will be returned to the user. As you can see here in this sample code. It's possible that the user denied accessing the information. It's possible that we can't get the position information. Or that we got a time out while trying to access the information. And based on this value, we can handle things a little bit differently. In the last demo of this module, we are going to add support for the geolocation API in our code. Demo: Geolocation In the last demo of this module, we are going to implement the find us page. On the find us page, I'm going to show a map of where the physical Joe's Coffee Store is located. And on that map, I'm also going to show how to get there based your current location. And finally, we'll also add driving directions in plain text. And course, we'll be using the geolocation API, part of HTML5. And a little bit of the Google Maps API. Let's take a look. I've taken the liberty to already add on the finder's page a couple of divs. The first div has an id map, the second div has an id driving direction. We'll first focus on the map div. I'm going to add a new script file and I'm going to call it geopositioning or something. There we go. Now in this JavaScript file, the main function is going to be to create driving directions map function. First, I'm going to check if the current browser has support for geolocation. I'm going to do that by checking if navigator to geolocation basically exists. If this doesn't return no. If this does return no, I'm going to show in the browser an error message saying that there's no support for geolocation. Now, we're going to assume that there is support, and if there is support, we're going to use the navigator.geolocation.getCurrentPosition. I'm going to pass in two callback functions, OnSuccess and OnError. I'm going to implement those in just a second. The third parameter is that position options that we saw in the slides. In here, I'm going to try and enable the high accuracy. I'm going to specify that the previous geolocation fix can only be a 1,000 milliseconds old. And the time out to wait is 500 milliseconds. In the unsuccess callback, I am getting in that position object that amongst others exposes the coordinates. I'm going to call in here the showMap function, which I'm going to create in just a second. Let's first add the OnError callback. Now in the OnError callback, I'm going to check which was the current error code. There's several possible options for this. For example, the permission can have been denied to access the location by the user. Or it could be that there is no way to figure out the position, there could have a been a timeout, or there could have been some other error. And in all cases we're going to get the div, to the map div. And we're going to change the inner HTML to specify what the error was. Now the next thing we need to do is implement that show map function of course, that is to show the actual map, based on our current location. Now, the last thing I need to do here is implement my showMap function of course. Another accepted two parameters are latitude and the longitude. As mentioned this is going to use the Google Maps API quite a lot. I'm going to show you a couple of things here but you can read a lot of this in the Google Maps documentation as well. I need amongst other directions service, and a directions renderer. Next, I need to specify, What is my route? The route has a couple of properties. Origin, which is the current location that I got back from the geolocation API. And I'm going to paste those in to a Google Maps, that long object. I specify the destination. In this case, I specified that the Joe's Coffee Store, is located on the Grand Market of Brussels. Which is not too far from where I live. And finally, I also specify that the travel mode is driving. Then I can also create an object that contains a couple of map options. The zoom level, where to center the map and, also, what type of map, which is in this case a road map. I want to show driving directions. And then the final thing I have to do here is create the actual map. This is again using the Google Maps API quite a lot. And save this now, and let's now go to the Find Us page. On this page, I have to add two JavaScript references. One to my old JavaScript file. And a second one that references the Google Maps API. Finally, I have to call my own function in my own script. And I'm going to do that again at the bottom of the page. I'm going to attach an eventListener that calls my create driving directions map up on the don't content loaded event, firing. Save all this and see what this gives in the browser. As you can see, the browser is notifying me that this local host page wants to track my physical location. I'm going to allow that. And there we go. We now see the map appearing, showing my location. As well as driving directions to Joe's Coffee Store, the physical store in Brussels. And there's one more thing I want to do here. I had that second div here, driving directions. I also want to show as text the driving directions from my current location to Joe's Coffee Store. So, in the geopositioning file, again, I can use the directionsrendered.setpanel. Which is actually going to take that div and paste in the driving directions. I'm not going to run this again, you can try it for your own, because otherwise you'll see my interests appearing inside of the browser. Let's go back to the slides. Summary We have reached the end of this JavaScript Focus Module. I think this module added a lot of interesting functionality to our site. And let's quickly review what we have added. We started by adding drag and drop to the shopping cart. Drag and drop is an operation which desktop users have been using for many years. With HTML5 adding support for this. Now comes out of the box. We have then added support for saving the shopping cart locally. For this we have used the web storage feature. Again, one of the new JavaScript libraries bundled with HTML5. Finally, we have used a geolocation API to find the location of the user. This was then used to show a map of the current position. So, this concludes Module 5 and in Module 6, we are focusing on the more visual side of things. I hope to see you there as well. Bye bye. Using Video and Adding Graphical Elements with a Canvas Module Introduction Hi, and welcome to module 6 of this Pluralsight course named Practical HTML5. My name is Gill Cleeren and you can follow me on Twitter via @gillcleeren. In the previous module, we've done a lot of JavaScript, to use some of the new APIs included with HTML5. In this sixth module, well, we are going to explore some more novelties in the platform. And yes, for a large part of the functionality, we'll again be using JavaScript. This chapter focuses on two of the more visual aspects of HTML5, mainly playing audio and video as well as using the canvas. The agenda for this module does indeed confirm what I just said. We're going to kick off the module by looking at how we can include in our site some audio and video. This is now with HTML5 built into the platform. Now of course this makes the life of the developer, again, a lot easier. In the second part of this module, we are going to check out one of the most popular topics that comes with HTML5, the Canvas. As mentioned, we will be writing mostly JavaScript to work with that Canvas. So after this module where is our site going to end up? We are going to add some video files into our site and we're going to do that so that users with all kinds of browsers will be able to play back that video. We'll also be including a graph, completely custom drawn using a Canvas and of course, JavaScript code. As we can see, the visual part of our site is going to be getting a lot of nice improvements in this module. Let's get started with audio and video. Hear and See with the New Audio and Video Elements When you look at internet data usage today you'll see that video data as well as audio data will take up the top spots. Daily millions and millions of video files are being watched on the web. I think we can't even start to imagine a world today without people doing crazy stuff and posting videos of this on the web. But how can we as web developers make sure that people can see these videos? While HTML5 now comes with support for audio and video, taking away a lot of several for web developers. Previously, to play audio or video content, HTML did not offer a solution out-of-the-box. We had to resort to other parties to be able to play audio and video content. Popular solutions include Silverlight, Flash, and quite a few others. And using these plug-ins, we were able to stream high-quality content to the connected clients. However, on both sides there were some issues. First, on the developer's side. The web developer had to work with yet another tool or framework, other than what they were using to build the web application itself. That can turn out to be an expensive task, since developers need to be trained, and support has to be guaranteed when something goes wrong. On the receiving end, so on the client side, users have to install the correct version of the plug-in and update them regularly, if they wanted to be sure to be able to see all the content. Now with HTML5, we can now play back content without using plug-ins. HTML5 comes with support for both audio and video, and the browser is doing the rendering without the user having to install any additional things. You'll soon see that these text are pretty simple. And using HTML, itself, only, we can only go so far. Therefore, a large part of the functionality is available, again, through a JavaScript API. We'll learn soon that the API is pretty capable. For example, we can even sync video with all our content, such as subtitles. The support for audio and video in HTML5 comes from not one but two elements which were added to the platform. These elements are pretty simple to understand. The audio tech has no visual representation. So there's no default media player skin. If you add an audio element to your page you can control playback but you won't see anything on screen. If you want to playback video of course, you'll use the video tag, which of course, has a visual, namely a player window. Don't think of this again as a media player with controls stuff by default. It is just a rectangle where you can play your video. On a side note it's possible to play audio with the video element and video with the audio element. While this works, it's definitely not a recommended practice, as it would confuse developers coming onto the project after you. Of course, the audio and video tags have some properties we can use to have an influence over the playback. First and foremost we need a way to indicate which content file we want to play. This we can do using the source attribute, src. The value can be an audio or a video file as you can see here in the sample code. The autoplay property allows us to control whether or not the media file should start playback on load of the page or not. By default this value is false, but we can control this behavior using the autoplay property. Here in sample code you can see that we are using autoplay equals autoplay, or simply add autoplay to control this property. By default, the media will only play once, but we can add the loop property on the audio as well as on the video tag. Another property available on both elements is the preload property. This property is used by the browser to check if it should all ready start downloading content while the playback hasn't started yet. So basically, this property controls the buffering type being used. None of course specifies that the content shouldn't start loading yet. Metadata indicates we want to get in metadata such as the length of the content. And auto means we'd like the browser to download the entire content file at page load all ready. As mentioned, the audio and video aren't player controls. The video element renders itself as rectangle played video. However, through the controls property, we can ask the browser to render player controls, such as a play/pause button, a volume control and the like. Simply add the controls attribute and you'll see the controls appearing. The last common property between the audio and video element is the muted property. Quite logically this attribute allows us to control if the media should be muted or not. You can see the attribute being used here in the sample code. The video element has a couple of properties which are not available on the audio element. For example, the width and the height properties, it's quite logical that these are not available for the audio element since that one has no visual representation. So by default, if you do not specify a value for the width and the height properties, the visual representation will be a rectangle with a width and height equal to those of the content itself. But what if we do not specify a video file at the loading of the page? Well in that case, the default values will be used and those are 300x150. If you specify only the width or the height, the video element will make sure that the aspect ratio is kept at all times. In the sample, we see that only the width here is set. This means that, indeed, the height will be set by the control automatically so that the aspect ratio of the video is kept. Of course, we can break the aspect ratio by setting both the width and the height ourselves. Although, in most cases, this is not recommended, of course. The video element also exposes the poster property. This can be used to point to an image file, which is loaded in the video element while the content hasn't started playing yet. Here in the sample code, we can see that the poster attribute is pointing to a PNG file which will be downloaded and shown while waiting to start the playback of the content. The only one video tag, are of course new, and all the browser's won't be able to render them. If you want to handle the situation gracefully, you can add fallback content. This is the content you place between the open and close tags of the element as you can see here, for a video tag. If you'd browse the disc coat with IE6, you'd see the fallback content being rendered. Since IE6 does not support the video tag. Up until here in this module, we've done the easy thing. We've defined one single source of content. In an ideal world, this would be enough. All browsers, although from different vendors would support the same content types and we would all be very happy. Sadly, we don't live in an ideal world and browser vendors tend to like to do things differently from others. For media content, this is definitely the case. As different browsers support different media types. That is why it is dangerous to write your code with just one source, and one media type, as it is very likely that some browsers won't have support for that particular type. How can we fix this? Instead of using the source or the src attribute, you can use a couple of source elements inside the audio or video tag. Take a look at the sample code here. When we see that we have defined multiple source elements, each with an src value of a different file type, it's important to keep in mind that these sources are evaluated top to bottom. So as soon as the browser sees one it supports, it will pick that one. If we want we can be even more specific. And instead of letting the browser guess the type by looking at the extension, we can specify the type ourselves as you can see here in the last sample on the slide. The last question before we take a look at the JavaScript API for this controls is then, which formats are supported? As mentioned before, this depends, definitely, on the browser and can also change over time. So be sure to check this information online, when you're watching this video, for updated support in different browsers. Depending on the browser, there is support for MP4 or H.264, WebM, and Ogg Theora when looking at video content. For audio content again, dependent on the browser, the support were MP3, AAC and Ogg Vorbis. With attributes we can control the playback only to a certain level. There will be a need to control these properties from the page we're on. So behind these controls, there's a JavaScript API available, which allows us to control most of these properties from code. For example, and quite logically, we can control the playback. Imagine that you want to build custom player controls, well, then you'll need this. It turns out that you can easily control the play back using play and pause methods and pause property. In the code you see here we are first checking if the video is currently paused, if so we start playing. And otherwise we can call the pause method, and we'll pause the video. Also, the autoplay property can be set from code. Simply setting the autoplay to true or false from code changes its value. If we want to be notified about changes in the media playback so that you for example, can change a play button into a pause button, we can use the play and pause events. In the code you see here on the slide, you can see that upon pausing the content recall a code to hide the pause button and show the play button. And in the play event handler, we do the opposite. From JavaScript, we can also control how fast or slow the content should be playing. And for this we have the playbackrate property. If we set the value smaller than 1 it will play slower. If we set it higher than 1 it'll play faster. Another property we sometimes need is the currentTime property. And it can be used to either check where we currently are in the content to update the text showing the current playtime. Or it can be used to set the content to a specific point in time so seeking. There are two more interesting properties in this area. The first one is the duration property. Quite logically, the duration property is used to fetch the length of the content. This can be useful to show the progress of the playback. And related to progress, is the progress event. The progress event fires automatically while playing and it fires a couple of times per second. And in combination with the current time and duration properties, this can be used to create a working progress bar. In the code you see on the slide, we see how the progress event is attached to a video element. Let's see how we can put this new knowledge to good use in the next demo, where we'll add a video to Joe's Coffee Store site. Demo: Adding a Video In this demo, we are going to add support for a video player inside the coffee details page. Notice that in the videos folder, in the solution, I now have two videos, named movie.mp4 and movie.ogg. Basically what I've done is I've created one video, and I've converted it both to an mp4 and a .ogg file. This way, the browser will get to choose whichever type it supports. Let's go to the Coffee Details page. I will add my video player, and of course, I'll be using the new video tag. I specified a width and height. I've also specified the poster frame which basically points to a image which will show when a video it's still buffering for example. In this case, I have also specified that the video should start playing as soon as the page is ready and the video has been downloaded. So the autoplay is set to autoplay. There are other properties which I have skipped for now. Of course this video tag doesn't know which movie should be playing now. So instead of pointing this video tag to one source I'm going to specify multiple sources. And I can do that by adding between the open and close video tag a couple of source elements. Notice that the first source element is pointing to the MP4 video and the second one is pointing to the OGG file. I also have fall back content. If the browser for any reason does not support a video tag, this text will be showing. Let's try running this. And here you see the video playing already. Now if I remove the auto-play again and we run it again, then we see that poster frame appearing. There we go. Now at this point the user doesn't have the ability to, for example, start playing the video. Now we can use the controls property on the video element, but instead I'm going to build my own little media player here using a JavaScript API. I'm going to start by adding a couple of buttons inside of this div. You'll see for example, a slower button, a back button, a play button, a forward button, a faster button, and a mute button. Next, of course, I have to write some JavaScript, and I'm going to add a new JavaScript file again. I'm going to call this videoplayer.js. There you go. I'm in my JavaScript file. I'm going to create a new function called initializeVideoPlayerControls. What I'm going to do here is attach functionality to the different buttons I've just added to my page. I going to start by searching for the actual video element by doing a document GetElementById passing in video player. Which was the id of my video tech. Next, I'm going to create a function called playVideo. And in here I'm going to check if the video is currently paused or if the video element is not doing any playback. And if so, I'm going to start playing the content. I'm also going to change the content of the button to pause. And if the video is already playing, I'm going to pause it again. We are also going to make it possible to seek in the video. I want to jump forward a couple of seconds or jump backward a couple of seconds. So in here I am going to see if the video is currently at the starting position. And then, I'm going to set it to the past ten number of seconds. Otherwise I'm going to increase the current time of the videos, so where it's currently playing, with the past ten number of seconds. Now as mentioned, I need to attach functionality to my buttons. The first thing I'm going to do is I'm going to search for my play button and I'm going to attach an eventListener on the clickEvent. Then I'm going to call the playVideo function. And that was this one. I'm going to do something similar for the back button. Which in this case is going to call the seek function passing in minus five, so I'm going to jump back five seconds. And I'm going to do something very similar for all the other buttons. So, we have the slower button, which is going to change the video playback rate. The faster button is going to increase the playback rate. And, for the mute button, I'm going to check if the video is currently muted. And, if so, I'm going to unmute it. And, otherwise, I'm going to mute it. So with this, I have my very basic player ready. I'll just go back to the coffee details page and add the script to this file. Finally, like we've already done a couple of times, I need to call onto my script. Let's run this now again, and now we should have some basic media player functionality. So by default, a video doesn't start playing and that's because I've removed that autoplay attribute. I can click my play button now, and the video starts playing again. I can pause it. Play again. Can also rewind. And also make it go a bit faster. I can also mute the video. So, as you have seen, we have now implemented basic video play capability in my page. Let's go back to the slides. Drawing with JavaScript on a Canvas Now that we have seen how we can show video content, it's time to take a look at some more, rich visual representations of content. Previously, it wasn't possible using plain HTML to show rich content inside of the browser. Simply drawing anything with HTML was impossible, there was no support for that. If we wanted to create the rich graphics we have to resort again to using a plugin such as SilverLight or Flash. With the same possible issues as we discussed before when looking at media content. Both Flash and SilverLight were added to an HTML page using the object tag. Now with HTML5 the platform gets native support for two types of rich content rendering, the Canvas and SVG. And in this module we'll use the Canvas. In Module 7, we will look at SVG. Now what is that canvas all about. As the name implies, the canvas in HTML5 is like a real world canvas, it's a drawing pane on which we can paint pixels in different in different colors. Hence building up a rich graphical representation, natively in the browser. The canvas in HTML5 can do more than a real world canvas. As it not only supports static content, but can also be used for moving content such as games. The canvas is pixel-based, we draw pixels on it. That means that it is not scalable, the content is getting a fixed size. We'll see in the next module that SVG, on the other hand, is scalable by default. Because it is based on vector graphics. The canvas in itself is a real simple element when it comes to declaring it an HTML file. We'll see that in a second. By default the canvas has no visual representation, it is just a look-less pane. So how do we then get that rich content on there? Well, all the drawing is done using a quite extended JavaScript API again. Very often, the browser allows the GPU, or the graphic processing unit, of the PC to render the canvas, and that is for performance reasons. And let's see how we can work with the canvas. As mentioned in terms of HTML, the canvas is really simple. You simply place the canvas element on the page, as shown here in the sample code. We can then specify your size and if we omit the size, it will default to 300 by 150 pixels. And that's about it for the HTML all the rest is done using the JavaScript API. Now in the JavaScript part there are a couple of steps we need to follow to start working with the counts. We'll always have to follow these as the first steps when interacting with your canvas. As the first step, we need to get hold of the canvas encode. And to do so, we can use a document.getElementById, passing in the ID of the canvas. We won't use a canvas directly in code to actually draw on it. Instead, we'll use an intermediate called the context. And we can get hold of the context using the get context method. Passing in the typeages in this case here 2d. With the context in hand, we'll soon be able to draw on the canvas. Now, one thing you shouldn't forget is just like with the video element. Adding fallback content for browsers who do not support the canvas element. Now, let's draw on our canvas. As mentioned, the canvas is a drawing plane and it has a coordinate system. The point with coordinates 0,0 is at the top left, so all the drawing starts from that point. In the sample code you see here on the slide, we are going to draw a filled rectangle. On the context, we first set the fill style to a solid color. Next, with this style active, we draw a rectangle using the fillRect method. Passing in the coordinates 0,0, the width of 100 and the height of 80 pixels. Another method is the strokeRect method, which draws a rectangle with just a stroke and no fill. The clearRect method clears a rectangular part of the canvas. Now while the clearRect method can be used to clear contents, in some occasions, we may want to clear the entire canvas. There's a little shortcut to do that, and that is setting the width of the canvas equal to well, the width of the canvas, as you can see here on the slide. Of course the world exists out of more than just rectangles. So we need to be able to get other things drawn on the canvas as well. More complex shapes than rectangles are created using a path. A path can be seen as a combination of several subpaths, and a subpath on the other hand, can be considered a number of points which form a line. And to a path, we cannot only add subpaths, but also figures. Let's take a look at some code to draw on the canvas. In the sample code you see here, we get hold of the context and then call the moveTo method. Passing in x and y coordinates. What this does, it moves a starting point for the drawing to that particular point in the canvas. Next we call the lineTo method, which will create a line from the starting point 100, 0 to the end point 200, 100. Finally, calling the stroke method on the context will actually draw the line. Let's take a look at a more complex path. In the sample you see here, we see that we are indeed creating a path, which consists out of several subparts. We first set the starting point for the drawing. The moveTo 10, 10. And next we call the lineTo method several times. This will create the several subparts. After that, we also set the fill style and call both the fill and stroke method, and this will draw us a red rectangle. To draw a circle, we have the arc method available. An arc method has quite a few properties to control how the arc is being drawn. But they are outside of the scope of this course. Now in the sample code here, we see that we are creating effectively an arc. This method accepts the starting coordinates, so 100, 100, the radius, the start angle, and the end angle, which are both in radians. Now the arc method in the previous example was just a border, we can of course, apply styling on the elements we are drawing on the canvas. On the canvas, the support for applying solid colors as well as gradients on elements for both the fill and the stroke. To apply such a style, we use the fillStyle method for the fill color, and the strokeStyle method for the stroke color. And as with other things in HTML, we can use the color name, the hex value, the RGB value, or the ARGB value. And a sample code you see on the slide, we are first creating an arc again. Then we set the fillStyle and the strokeStyle. And only after that, we can call the fill and stroke methods on the context. This will then draw the arc with the style specified in the strokeStyle and fillStyle methods. Next, we change the fillStyle and call the fillRect method, which will take the currently applicable color for filling the rectangle. So as you can see, the canvas will always draw the new items with the current set of styles. As mentioned in the previous slide, it's not only possible to apply solid colors and elements, we can also apply gradients while drawing on the canvas. In the sample code you see here, we are first creating a gradient using the createLinearGradient method. This doesn't do anything yet. We're just creating the gradient. And we are specifying its position and size. And it is may seem a bit weird. We are creating the gradient for a particular area in the canvas and will later use that gradient as a fill for an element we add to the canvas. Next, we are creating the color stops for the gradient using the addColorStop method. This accepts relative values and for each of these, we specify what a color should be in that position. We're adding three color stops here, red, blue and green. Finally, we specify the created gradient to be the currently applicable style using the fillStyle method again. And then, we then use the fillRect method where we'll draw with the just created gradient. Now, notice that you don't see any of the green part in the gradient. That is because, like I said, the gradient is created for a particular area and our rectangle is smaller than the gradient's area. The canvas isn't limited to working with items we create on the fly such as rectangles or arcs. We can also load images into the canvas to create more advanced graphics with the canvas. Drawing an image is done using the draw image method on the canvas which accepts the image we want on the canvas and the position, in this first overload of the method we see here on the slides. Now how do we get an image on the canvas, you may ask. Well again, the answer lies in JavaScript. Take a look at the next sample code here. The image we want to load in is part of the HTML DOM. So we can retrieve it using the getElementById again. Once we have the image, we can pass it to the draw image method to draw it on the canvas. The image on the canvass, just like everything else on the canvas, is just a collection of pixels. We can start deleting parts of the image, for example, using the clearRect method again. The drawImage method is also overloaded. In the next code snippet, we are using the draw image with five parameters. This directs of parameters allow us to specify the size of the image in pixels on the canvas. Now, next to resizing, the draw image also allows us to basically zoom in on a part of the image and draw the selected part, well, a bit bigger. To do so, we can use the overload you see here on the snippet,which accepts a total of nine parameters. The parameters starting with an s are the values where to clip the original image. The regular ones specify where to draw the image on the canvas. Quite logically, there will be occasions in which we'll want to add text to our canvas. There are two simple methods available to do so. The fillText method, which creates solid text and the strokeText method, which creates just the outlines for the characters. In the first sample code on the slide, we can see that we are first setting the font for the creation of the text. Next, we call the fillText method, and we get solid characters. In the second sample, we're doing exactly the same, but now we're using these strokeText methods. Notice in the screenshot, that the characters are now just an outline. Two small things before we'll apply our canvas knowledge in the demo. The first one is transformations in the canvas. We've already seen autotransformations in HTML5. In the canvas, transformations are basically changing the grid of the canvas. For example, we can apply a rotate transform, and what this will do is changing the angle of the grid on which we draw. And if we do a translation, removing the zero, zero point and all of this results in very cool things that we can do with the canvas. Let's take a look at this in some code. The rotate transform, I can just set, basically, rotates the grid on which we draw. And the translate moves the starting point. Here were are first asking the context to translate to move the origin to the center of the canvas, using the translate method. Next, we are rotating over 45 degrees. Then we simply draw, like we've done before but now we are drawing in a changed rate of pixels. And the result is that the rectangle is rotated and drawn in the center of the canvas. We can also scale the grid system. Notice in the sample here we are using the scale method to scale the context. We are scaling to half the size in vertical position. When we then draw a square, we end up with a rectangle. Since the pixels in vertical size are scaled to half their original size. The final thing I want to show you for the canvas' state mechanism we have available. It's possible to store on a stack the current settings of the canvas so that we can re-use them later on. And to do this, we have the save and restore methods available. Take a look at the sample here. Initially, we set the fillStyle to yellow and draw a rectangle. We then called a save method so the current state or settings of the canvas are stored. We then use red, save the red setting and then use blue. After that, we'd like to continue with the settings we had before the blue one. So we call this restore methods. This pops the blue settings out of the stack and we can continue using the previous one. Let us now go back to our demo. We'll use the canvas there to draw a graph to show the statistics of sales of a particular coffee. Demo: Drawing with the Canvas In this demo, we are going to add the canvas. And we are going to actually use the canvas to show a graph of the sales for a particular coffee. So we are again going to make changes to the coffee details page where we are going to add this graph. Of course, we need to start by adding the canvas. So here is my canvas. I've given it a width and a height, and I've also specified some fallback content. Basically saying to the user, sorry, but your browser does not support the canvas. You need to upgrade. You cannot see this sales graph. Now for the rest, there's very little I can do with the canvas itself. I need to work again with JavaScript. So we're going to start by adding a new JavaScript file. So in my scripts folder again, I'm going to add a new JavaScript file, called canvasChart. There we go. Now in this demo, I'm going to work with some hard coded sales figures. In a real life application, this should of course be downloaded, for example, using Ajax. So in here I have my coffee sales for a period of 12 months. Specifying how many times each coffee has been sold. And the graph I'm going to create is a bar chart. Typically such a graph consists out of a couple of axis, as well of a couple of bars. I going to start by creating a function that can create my axis. Now this createAxis function accepts the context which will be passed into actually do the drawing. The start in the x and the start in the y-coordinates. And the end x and the end y-coordinates. So what I'm going to do is basically draw a line here. On the context I'm going to call the beginPath, saying that we're going to start the drawing. And I'm going to move to the start in the x and start in y. That's the starting point for this path. I'm then going to say that I want to create a line to the ent, x and ent y point. Call the close path. And finally, I'm going to call the stroke on the context. This is going to make a stroke from the start to the end point. The line is going to be drawn. Next I'm going to create the createBar function. Which now accepts an x and a y for the starting position of the bar. So, a rectangle. And a width and a height for the rectangle. So this is very similar, and I'm going to use the rect function passing in that starting point, the width and the height. I'm now also going to call the context.stroke. As well as the context.fill. Which is going to use the current fill to fill my rectangle. So we're now ready with the helper functions. I'm now going to add my drawChart function. And the drawChart function is the function that I'll be calling for my page. As the first one, so the first thing I'm going to do is get hold of the canvas by using again a document.getElementById passing in the bar chart id. If the canvas is not null and the getContext actually works, returns something basically. I'm going to get hold of my context by calling canvas.getContext 2d. Then I'm going to call to createBarChart function. Passing in my context, and my data, and some other setup data that we'll see in just a second. In the createBarChart method, I received the context, the data, the starting point in the export drawing. The bar width and the height for the entire chart. I specify the line width to be 1.2 pixals. And I also specify the start in the one. This line width is going to be used to do the drawing of the axis. So, I'm going to call my createAccess function twice. Passing in the context and some parameters where the actual drawing is to be done. Now this context line width is going to be used because in my createAccess I'm just calling the stroke and this is the current stroke line width. Next, I set a context line width to zero. Next, for each item in the area of data, I'm going to call to draw a bar chart. I'm not going to take you through all of this. The most important thing here is that I'm setting the fillStyle to blue. I'm calling my createBar function passing in parameters over to draw an actual rectangle. And finally, I use my context to also put some text below the horizontal axis. And what I'm going to put there is the name of the month. In the coffee details page I need to call my script. And also, at the bottom of the page again, I need to call now my Chart function. Let's take a look at this in the browser And here at the bottom of the page, we now see our bar chart being drawn. You see the axis, the vertical one and the horizontal one. You see the x labels at the bottom of the page. And for each point, we see a bar chart representing the number of sales for that particular month. All of this is done using the canvas. So, all of this is pixel based. It doesn't really scale. Let's go back to the slides. Summary This brings us to the end of Module 6. We have one more module to go. But before we start that, let's summarize what you have seen in this module. We started the module by looking at the new support for audio and video in HTML5. Using this support we can play back media content without having to resort to plugins. We also have looked at the support of different browsers for different content types. Which sadly, is not a great story. Next, we have spent a lot of time exploring the Canvas API, which is mostly JavaScript based functionality. It becomes possible to support rich graphics in the browser. As set, we have one more module to go, which will focus on SVG. I hope you are joining me there, as well. Drawing More Graphical Elements with SVG Module Introduction Hi, and welcome to the last module of this Pluralsight course named Practical HTML5. My name is Gill Cleeren and you can follow me on Twitter via @gillcleeren. In module six, we have discussed both support for audio and video in HTML5, as well as adding rich graphics, using the Canvas. As we have seen there, the Canvas is capable of quite a lot of interesting features. However, it is pixel-based, which means that if you want to make your graphics scale out, it'll be a manual job for you to do. If you're after scalable graphics for your site, you can take a look at SVG, scalable vector graphics. SVG is the focus of this last module. As set, this module focuses entirely on SVG. We'll start first with the exploration of the SVG feature, and we'll add some SVG graphics to our site. Next, we'll take a look at the support for animations in SVG. So, at the end of this chapter, we'll have added more graphical aspects to our site. In the previous module, as you remember, we have created a bar chart, using the Canvas. In this chapter, we'll add a bar chart as well, but this time using SVG. And next we'll add some animations in this bar chart as well, of course again using SVG. Adding SVG Graphics to Our Site So let's now start the chapter with the exploration of SVG. In this first part we'll take a look at the most important aspects of this HTML5 feature. And before we do so, let's first get a clear picture of what SVG really is. As mentioned, SVG stands for Scalable Vector Graphics. The name gives a way what the most important aspect of SVG really is. We are working with scalable graphics. Now to have scalable graphics, we cannot work with pixels, with bitmaps that is. Instead what we need are vectors. An SVG graphic doesn't really contain pixels. It contains instructions that allow the browser to create the drawing for you. Since we're working with instructions, things can be rolled back as it is the browser who's constantly updating the drawing for you. Of course we don't work with these instructions ourselves. To create SVG graphics, we work with an abstraction. SVG is an XML-based language. All the graphics are created declaratively. It is therefore comparable with demo. SVG has its own DOM, and we'll see that soon. Indeed, SVG blocks are declarations in a separate DOM, within the main HTML DOM. In the small sampled code here, on the left of the slide, we see an HTML DOM, and inside it we see a separate SVG DOM. A page can, of course, contain more than one single SVG DOM. The SVG DOM itself is not an island, as it interacts with the surrounding HTML. It's perfectly possible to include graphics, as well as animations in the SVG DOM. SVG's part of HTML5 and is now an official W3C recommendation. if you've been a web developer for quite some years you may remember that SVG isn't really new. It was already created in 2001, but has never really taken off. Now being part of HTML5, there's much better browser support for it. Most features we'll discuss in this chapter are compatible with all major browsers. On this slide here, we see again there're very small sample that we saw on the previous slide, already. The sample contains an HTML DOM and inside it you can see an SVG block. As mentioned, this is the SVG DOM declaration, inside the SVG element, we are going to build up our SVG content. The SVG itself is part of the layout of the page and therefore gets a width and height. Now what can we place inside the SVG element then? Well we'll start just like with the Canvas, with some basic shapes, which are really easy to create. There's a similar list of basic shapes available. If we want to create, for example, a rectangle, we use the rect element. In the code sample you see here, we see that within the SVG block, a rectangle's being created and is placed on coordinates 10,10. It also gets a width of 100 and a height of 100. Similarly, we can create a circle, for which we have to declare a center point as well as a radius. An ellipse declaration also requires that we create a center point as well as a radius, and the x and the y direction. We can also create a polygon, which is a closed shape for which we can declare the points as you see here. A line can be declared with two points or as a polyline as a collection of points. If we need to create a complex shape we probably won't get there with the above elements and probably need to use a path. Paths are very complex to create by hand and therefore are often created using a drawing tool. Finally we can also add text using the text element. To add text we need to specify where the text needs to be placed using the x and y coordinates. Between the open and closed tags we then specify the actual text. In the following slides I'm going to give you some more examples of SVG graphics with some more code. On this line here we can see the complete listing including the HTML DOM to create the red rectangle you see here on the slide. The SVG block is declared within the body of the HTML DOM, and inside the SVG block he have a rect declaration including the rect fill color. Both of them also have a fallback declared inside of the SVG block, so we can notify users that they are using a browser which does not support SVG. In this sample here we have a couple of eclipses. All though you can think it has some special effect going on here, the image that you see here can be created using three simple eclipses. Notice indeed, inside of the svg element we have three eclipse elements being added. Each has its center and radius in both horizontal and vertical x's defined. We can also create a more complex shape using a polyline. As mentioned, the polyline is a collection of points. In the code here, we see the points for the polyline declared in the points attribute. SVG can also fill the graded shape as you see here, in this image. By default, it will fill the graded shape with the black color. We can, of course, with SVG go further than just adding a couple of rectangles or ellipses on screen. We have quite a few formatting options available to us. For example, we can change the way a simple line is shown on the screen. We can change the stroke, the stroke-width, the linecap and the dasharray. In the sample code you see on the screen, we've created a dashed line. The line uses dashes of 10, 10, meaning ten pixels are blue and 10 pixels are transparent. Also we have added a line cap and set it to round. We can, of course, go a bit further and make a more complex dasharray as you can see here in this second sample. Notice that we have created a different dasharray in the code. Also things like the basic rectangle can formatted differently. For example, the rect element exposes the fill as well as the fill-opacity. The fill accepts a color. And the fill-opacity accepts a value between 0 and 1. The lower the value, the more transparent the shape will become. Now, SVG also supports grouping of elements. For this, we have the "g" element. In the sample here we can see that we have a "g" element around a couple of other elements. When we group elements we can apply a style, all elements of the group. In one go. It's possible also to nest groups for even more control. Now SVG has more advanced effects we can apply on its elements. For this we can use filters. As the word filter implies using a filter we can apply one or more graphical changes on an SVG element. SVG comes out of the box with a number of predefined filters. So how do we apply such a filter? Now filters are declared in a so called defs block. Defs contain definitions of resources which will be referenced from elsewhere in the code. This way the filter can be defined once and used multiple times inside the page. In the sample you see on the slide, we have a defs block at the top and inside of it, we have a filter being declared. Notice that the filter does have an id defined. That's required. In this slide, we don't have an actual filter edit yet. We'll add it in just a second. Secondly, we have a rect element, and on that rect we are going to use the filter attribute, and as the value, we specify a URL and then the ID of the filter within the def's block, and that filter will then be applied on the rect element. Like I said, there are a couple of filters built into SVG. You can see the list here. Of course we don't have the time to look at all of them in detail, so let's pick out a couple of interesting ones to apply to our rectangle. A blur, more specifically a GaussianBlur, can be applied on an SVG element using a filter. You can see the end result on the right here in this slide. So how do we create that blurred rectangle then? Take a look at the code, and you'll see again at the top of the SVG block the defs element within there, the filter declaration. We specify that you want to apply a GaussianBlur, using the feGaussianBlur filter. Filters have attributes, as well. The deviation parameter influences how blurry the image will be made. And on the rect element, we are applying the filter using the filter attribute again, passing in the name of the filters with a id attribute. Now one filter can be the combination of several effects. For example, we can create a drop shadow. Now there is no built in effect for this. However, we can combine a couple of other effects to get it. So basically we are chaining the effects. Take a look at the code here and notice that we have a filter within there and feOffset, feGaussiabBlur and feBlend. feOffset is used first and basically offsets the original image over a certain distance. The output of feOffset serves as the input for the blur effect. Now, the blur is an added and thirdly, the output of the blur effect is used as the input for the feBlend. The latter will blend the original image and the offset image. That is the one with the blur effect applied on it. And we've all ready seen solid fills that we can use to color an element. Next to solid fills, SVG also supports gradients to use as fill style for elements such as rectangles. More specifically, SVG supports linear gradients as well as radial gradients. One thing before we look at just like filters, gradients are defined inside of a defs block, so they can be reused multiple times within the SVG DOM. Let's apply a linear gradient. On this slide here, we are creating a gradient to fill an ellipse. The gradient we are creating here is a horizontal gradient starting on the left and continuing to the right. So the default. First take a look at the defs block where we are defining the gradient using the linear gradient element. The first giving in an idea. Next we define the direction using the x and y values. For these values, a percentage is expected. Notice that the x value goes from zero to 100% which is why we are creating a linear horizontal gradient. Next we define the color stops and for each stop, we need to specify where. So at which percentage the color should be visible in full. Finally, we're going to apply the gradient on the style using the fill property which now points to the ID of the gradient. If you want the gradient to be vertical, we simply have to specify that the value varies in the y direction, as you can see here in the sample. Let us now turn our attention, again, to the coffee store site and add some SVG code. Demo: Adding SVG Graphics to Our Site In the previous demo, we have created this bar chart using a canvas. And in this last module, we're looking at SVG, and we're going to try to recreate this same bar chart but now with SVG. Let's take a look. So in this case, we're not going to be using any JavaScript. We're going to create the entire bar chart in a declarative manner. So we're going to start by creating the SVG block in which we are going to create our chart. So I've added this SVG DOM within the main DOM of our page. One of the first things that we did with the canvas was creating our access. And now we're going to do exactly the same. In a declarative way, I'm going to add two lines here, which are going to be the actual axis. The parameters are the starting point, the end point, the stroke, which is in this case black, and the stroke width. With the axis in place, I'm going to create a bar for the bar chart. Such a bar is need a rectangle with again, a starting point, a height, a width and a fill. All the other bars are pretty similar. I'm going to paste them in here. As we can see now I've added 12 rectangles. If you remember, in the canvas we also had some labels on our chart. I'm going to do it down here as well. If you remember correctly, in the canvas bar chart \we had some labels at the bottom of the bar chart. We're going to do that here as well. And we're going to use the text element for that. Such a text element also gets a position where it needs to create the actual text, a fill, and then the actual content. And in a similar manner we can add all other labels for all other months. We'll add some more labels here. Now these labels actually display the value of the bar chart so the number of sales of that particular coffee for each month inside of the chart. Let's take a look at the resulting bar chart. This is the canvas one, and this is the one that we just created now, using SVG. As you can see I have actually not added 12 bar charts, I've only added 11. We're going to add the 12th one in the next demo. Adding Animations Using SVG In the second and last part of this module, I'd like to discuss SVG animations. One important thing to note here is that SVG animations are not supported at the time of the creation of this course in Internet Explorer. So, be cautious when you are using them. We're looking at SVG animations. We basically have the choice to either add an entirely declaratively or using JavaScript. Declarative means that we are creating it entirely using SVG code. That is the solution we are going to use in the remainder of this module As mentioned, SVG animations are entirely defined in markup. That means that either the developer basically defines the instructions for the animations and it's the browser who is doing the actual animation. So when we are creating a declarative animation, we are using only SVG to do this. And we think of an animation, when I was doing it. Animation runs for a certain amount of time. So in the SVG animation, we definitely need to include how long the animation will take. Also in the animation definition we need to include which element we want to take part in the animation. And based on this information, all defined in SVG, the browser can render the animation. I think it's quite logical that time is important in an animation. An animation is basically the change of a value of an element over time. An animation needs a beginning and an end to know when the animation should start and when it should stop executing. Typically, we specify animation in the form of start the animation ten seconds after loading the page. Or start the animation when another animation has finished. The begin and end in an animation can be set to just a number which defaults to seconds. If needed, we can also use numbers including hours, minutes, seconds and even milliseconds. So 03:30 would mean 3 minutes and 30 seconds. And note it's also possible to specify the duration of an animation using the dur property of the animation. Only defining how long an animation would run is not enough. We also need to trigger the actual animations start. And this can be done using a trigger to fire the execution of the animation. There are different types of triggers included in SVG. For example, a animation can start when another animation starts or ends. Also it's possible to start a animation from code, so on a button click or on a key press. If you don't specify anything the SVG animation will start automatically on load of the SVG document. SVG comes with a number of possible animation types. We'll take a look at some of these and then apply them in our site. The simplest form of animations is the set, which simply switches a property from value A to B. Other animation types include animate, animate color, animate transform, and animate motion. Let's take a look at these in a bit more detail. So a set, the set animation simply switches the value of a property at some point. So it's not really an animation. It is just switching a value. There's no transition or something else possible here. So here in the sample we see a circle and then a set animation inside of a circle. This animation simply changes the value of the fill attribute to orange after one second. The second sample here uses again a circle, but now uses an animate instead of the set animation. The value of the center point in the X direction will allow change from 30 to 100 at load of the SVG block, over a time span of ten seconds. That is the duration. The fill property is set to freeze, which means that it keeps the end value of the animation after the animation has finished. We can also move elements around using the animate motion animation. In the sample you see here, we have a rectangle and we've added the animate motion. The target position is set to 150 in the x and 50 in the y direction. The animation starts on click and will take three seconds. In this last sample here we are using the animate transform animation on a rectangle. Which will basically transform the element. In this case, it will perform a rotation. Over a time span of ten seconds the rectangle will rotate over an angle of 90 degrees. Let us now go back to the sample and add an animation in our graph. Demo: Adding Animations Using SVG In the very last demo of this course, we are going to work with SVG animations. Remember, that in the previous demo, there was actually one bar of the bar chart missing. Well we're going to make it appear now, using an animation. The one I'm talking about is actually in the SVG, but it has a height of zero. And also, it doesn't have a fill applied on it. I'm going to give this one a gradient. If you remember from the slides, gradients have to be created in the def block. So I'm going to start by creating a def block, through a definitions block. And inside of it, I'm going to add a gradient. In this case, I'm opting for a linear gradient. And from the attributes here we can see that this gradient is going to go from the bottom to the top. Now for the gradient, I'm also defining a number of calls stops. This is the call at the starting position of the gradient and this is the one at the end position of the gradient. The next thing I'm going to do is apply this gradient onto that rectangle. So I'm going to use the fill and I'm going to set it to URL. Passing in the id of the gradient within the definitions block. And that was simply gradient one. Now it still doesn't have a height. I'm going to use an animation for this. So I'm going to say that I'm adding an animate here. And the attribute that I want to apply my animation on, is indeed the height. And the value needs to go from its current value to a value of the sales number for that month. Which is 689. I'm also going to specify the fill. And I'm going to set it to freeze, which means that the end value remains visible. So it's going to stay at 689. Finally, I need to specify how long the animation should take and let's put that to five seconds, for example. If we now run this in Internet Explorer, we're not going to see anything happening. Because at this point Internet Explorer does not have support for SVG animation. So be careful. I'm going to use Google Chrome instead. And so, this is now the result in Chrome. Let me zoom out a little bit. If we refresh the page, on load, the animation starts and goes from yellow to red using that gradient. Summary and Course Closing With this last demo we have finished this chapter. And actually, also the course. Let's go over what we have learned in this module. SVG is a welcome addition to the HTML5 platform, making it capable of also creating scalable vector graphics. With many high resolution devices appearing every day, this is something that is highly required. SVG animations also extend the features, making it possible to go beyond static graphics being created. And this concludes this Practical HTML 5 course, as well. Let me be the first to congratulate you on completing this course. It has been a long ride, but I'm confident that you have learned a lot of useful things. Please make sure to download also the source code as well. As it will help you with one of the primary goals of this course, capturing the big picture of how all HTML 5 features can work together. I want to conclude by thanking you for watching this Pluralsight course. And please contact me with any questions you might have or leave a rating for this course on the site. Thanks for watching bye bye for now. Course author Gill Cleeren Gill Cleeren is a solution architect, author, and trainer in mobile and web technologies. He's also a Microsoft Regional Director and MVP. He lives in Tienen, Belgium. Course info LevelBeginner Rating (764) My rating Duration4h 6m Released24 Feb 2015 Share course