Front-End Web Development Quick Start With HTML5, CSS, and JavaScript
-
Why This Course?
If you're just starting this course you know that you need to learn some web development skills and this in course in particular is to help you learn HTML, styling with CSS, as well as client side code with JavaScript. The purpose of this course isn't to give you a deep breath of knowledge, but to allow you in a couple of hours to really understand the basic concepts of HTML, CSS, and JavaScript. Instead of lecturing you with a lot of slides we're going to focus most of the course on some practical, hands on examples. We'll be walking through a simple website example and show you how to build up HTML, change the way it looks with CSS, and then finally write some code to actually interact with the user and with network requests using JavaScript. If you've been apprehensive about learning web development don't be. Lots of developers from different eco systems have sort of shunned web development because of the horror stories they hear from web developers about dealing with multiple browsers, dealing with a fear around CSS, and dealing with JavaScript as a language. Hopefully in this course I'll dissolve most of those fears and show you that it's really a pretty ecosystem these days and that developing cross browser applications isn't nearly as difficult as it once was and hopefully I'll also dissuade you that JavaScript isn't a first class language that you can build great softer with, that it's predictable, testable, and actually fun to code in. Let's get started with HTML.
-
What Is HTML?
The first skill you're going to need to learn is HTML. And HTML is a markup language, a structure of what an individual webpage is supposed to look like. Now HTML is a bit different from some other ecosystems you may be used to working with in that it has been built up through years and years of making concessions. HTML, when we start to look at it, is really a standard built by the winners. Early on a lot of the decisions around HTML were driven by the browser companies that decided to implement things one way or another. When successful browsers had implemented certain features it was hard to backtrack as people were coding against those browsers and had active webpages that were actually working. HTML doesn't always make the most engineering sense, but having the understanding of how these decisions were made means that you can forgive them a little more and knowing all the different rules will be enough to help you understand HTML5 in general. When we talk about HTML5 a lot of technologies get lumped in under this moniker of HTML5. Start talking about CSS3 and features of browsers like index databases and file APIs and touch events, as well as the changes to markup and those sorts of things, even things like web storage or web SQL were lumped under this heading of HTML5. We're not going to be talking about all these related technologies. As you learn web development, especially client side development, you're going to learn a lot of these details. This course will cover JavaScript and CSS, but we're not going to cover the breadth of what some technology companies have decided to call HTML. Instead we're going to focus on the markup language itself, on the angle bracket language that browsers can interpret and then draw on the screen. So this brings the question of what is HTML itself? HTML stands for HyperText Markup Language. It's been around for a very long time and essentially is an angle based structure language that allows you to define different parts of a page, some visible to the users and some not visible to the users. It's derived from the SGML language, which simply defined general purpose markup languages, that's what really brought in the angle bracket structure that we see today in HTML. For example, this is a very simple HTML document. It starts and ends with tags that are enclosed in angle brackets. These tags have a hierarchy structure to them and it should always start with the top level HTML container. HTML contains a head that contains some metadata about the document and then the body, which is the visual representation of what the user will actually see. And we'll learn what each of these tags mean more in detail when we start to look at actually building these using a text editor. For some developers who have been out there and working in different systems before, they see the angle bracket markup language, like HTML, and assume it's going follow the same conventions that XML does. It is not case sensitive and it has mixed closing rules. If you are already familiar with XML this can actually ____ an HTML. For example the script tag you see here can't be self enclosed like the image tag here, it has to begin with a script tag and then end with a script tag, even if there's nothing in the body of that tag. Adversely the image source and some other elements can never have a body, they only describe a site of properties. You'll see this more concretely as we start to build our own HTML pages. HTML relies on something called the Document Object Model. This is basically the hierarchy of elements within an HTML page. While this hierarchy of elements is how you describe a page, at runtime it also represents an object graph. As we look at the markup of an HTML page it's really a graph of elements that represent the things that the user can see and interact with, but also a set of objects that you as a developer can interact with. So a document contains a head and a body section. Head might contain other objects like the title section. A body might contain headers and section objects that can contain other elements themselves, and so on as we start to break this down. So we should really see the document object model as a representation of the objects that are available to the browser and to the client code. Let's see how this is working in actual practice.
-
Hello Markup
So let's start by understanding the simplicity of markup. For our examples I'm using a Sublime text editor to just write plain old text files. I could be using Notepad, I could be using Vim or Emacs or any editor including Visual Studio. What we're doing is just creating simple files that we can host as a small website, it doesn't matter what tools you're using. I like using Sublime in this case because it's really thin and easy to see all the moving pieces. So here we have a really blank slate. When we're dealing with markup, we're really just talking about creating a hierarchy of elements. So let's just create not even HTML at this point, just some markup. So some of the basics of markup is that you can have an element, and an element is a name of an object and it's surrounded by two angle brackets, a less than and a greater than. And in this case that represents the beginning of this structure. To end an element you're going to start with that same greater than and less than with the same names we have here, but you're going to start it with a slash in front of it. This is an indication that this is the ending part of this, what is called an element. And then everything inside of that is simply the content of that element. And in addition you can have what are called siblings and that is elements that are at the same level that are sisters or brothers of the other elements. So let's do that with a bar element here. So in the case of bar we might not have any content and while it's perfectly valid to leave the beginning and end part of the element just next to each other, some of the elements support what are called self closing tags and that is ending an element with a slash greater than. This indicates that it's an object, but it's an object that has no content inside of it. It's a simple, atomic element. In most cases instead of having arbitrary content, markup will have a hierarchy relationship or a parent child relationship. So in this case foo is the parent of the bar element and the bar is the child of the foo element. So a simple parent child relationship. And this is how you can build hierarchies, one parent has another child, has another child, has another child. And it's perfectly valid to have let's say a couple of these. And so in this case, foo as a parent has multiple children. And these are some of the very basics of markup itself, but we're really talking about HTML as a markup language, a hypertext markup language. So instead of these arbitrary elements, let's use elements that are actual HTML markup elements. So here I'm going to change this top level parent to a div. A div is a basic unit in HTML that says this is a portion of my webpage. Inside that div in an HTML page we might have an image tag as well as let's say a paragraph tag. P is for paragraph. So in HTML we can have these atomic elements and image is one that is always atomic, it never has content associated with it, and then paragraph tags that may have arbitrary content. In this case I have some piece of text that's going to be shown in a formatting for a paragraph. And so this is about the most simple piece of markup we could possibly have in HTML. Even in content scenarios you can have other parts of the content wrapped in their own element. For example if I say hello world and put my name in there, I could surround the world with a b tag or a b element as it's often known, and that is going to be some indication of how I want a formatting the world and in this case that would be bolding of that text. So even in the case of content with HTML we're using elements to surround or to tag different parts of the markup so the browser knows what to do with them. Elements themselves can also have what are called attributes and these are pieces of information, name value pairs typically, that are inside of the actual element tags themselves. So I could define that this div has an idea of top and then image could have an attribute called source that pointed at some actual source location for an image. Individual elements can have more than one if necessary, like in the case of image tags we might have a second attribute that defines the alternative representation of this image for viewers that have images turned off. This is often the case for screen readers for the blind or for the partially blind. Now if you've come here with some prior knowledge of markup languages like XML, you want to be careful with understanding this markup. Because in the case of XML there are some rules around XML. XML was actually developed after HTML and wanted to find something that was a little more structured than HTML. HTML has some specific peculiarities that make it a little bit more difficult to parse than pure XML. So if you come from the XML world one thing you have to realize is that unlike XML the markup here in HTML is not case sensitive. So making a capital img for the image tag is perfectly valid. Most people use lowercase tag names, but it is not a requirement. There's also this notion of being able to self close a tag like we have here on image, but not all elements support that. There are tags like script and paragraph and div that must end in a full element closing like this. They cannot end in this shortcutted version. And there are some elements like the image tag that can't have its own content. It never has children. These peculiarities can throw you because in the XML spec they standardized these things so they were a bit easier to parse. In HTML you're just going to have to learn about these exceptions and live with them. We're living with them, we can't just change it because we have browsers that go back years and years that have existing websites that are relying on these rules to be in place. This is one of the peculiarities of web development that can be a little painful, but most of the libraries, most of the code we're going to be using, are going to have ways to sort of backfill older browsers for us anyway. So let's take this and let's start building our first HTML page, now that we've looked at some basics of actual markup.
-
Structure of an HTML Page
Next, let's create an HTML page from scratch so we can see the real structure of an HTML page. I'm going to go ahead and close this temporary file and I'm going to create a new file. I'm just going to call it index.html to represent just a simple HTML page. HTML pages start with a tag called HTML and that is the parent for the entire HTML document. Inside the HTML document there is a head section and this is going to contain some elements that are used to interact with the browser, setting the title, bringing in CSS sheets, setting metatags, things that aren't really about the look and feel of the individual page. For the actual body of the document we're going to have another tag called body. This structure is the very skeleton of an individual HTML page. An HTML parent called HTML that contains two elements, a head and a body. Before the HTML tag we start the document out with something called the doc type. This is a bracket, exclamation point, and then the word doctype to indicate what is the actual type of this document. So this doc type is going to indicate what kinds of elements a browser is going to expect in your document. If you include element types it's not familiar with, it's actually going to interpret them, most browsers do at least, as div elements. So if you want to have your own named elements, they will be interpreted for the most part in modern browsers as a div element itself. So let's go ahead and make an actual working HTML page here. Right now we have a valid HTML page, but there's nothing at all that's being displayed in the browser. First thing we'll do is start with the head and we're going to go ahead and give our document a title called the Github Hub so a simple webpage that's going to look at the different projects on GitHib.com and be able to look at information about them. Not a super useful webpage, but for us it's going to introduce a lot of these concepts. In the body itself let's start with what's called an h1 tag. H1 is a heading. There are actually six of these that are defined with HTML. H1, 2, 3, 4, 5, and 6, for different heading levels. H1 is normally the largest of these and it's used for big visual elements on the page. So let me put that same name here, Github Hub and let's actually view our HTML page in the browser. So as I go to our index.html page, we'll see a couple of things here. This is that h1 we defined that is part in the body. The body is going to exist here in the main part of the browser, but one of the other things you should notice is that the title ends up being the title in the tab or in the title box of the browser. Most browsers now are tabbed, but even in the case of non-tabbed are only individual pages in a browser, you going to see that titles show up right here in the tab. So the title is important, it's not just a piece of record keeping, it's actually something that is displayed to the user. If I go ahead and bookmark this item, that bookmark is actually going to be the name that was in the title, Github Hub. So that title element is important to get and get right. And now back here let's add a paragraph tag just to indicate some information. This is a site to search Github for interesting projects. Let's go ahead and create a second paragraph tag that might have a little bit more information. So now we have just structural information. We have a heading and then a couple of paragraphs. If we go back to the browser, we'll see that it's separated these into something that sort of looks like paragraphs. If we make this smaller we'll see that the paragraphs will actually text wrap as you would expect paragraphs would in any sort of textual representation. But we'd like to have some more information here that might be interesting. So let's go ahead and use another tag around here, around the sample site, that says go ahead and show this in italics. And then let's go ahead and do the same here for bold. So these are elements in their own right, but they are also information to the browser to indicate how to format what the user is saying, in this case use italics and in this case go ahead and bold those elements. And we can now see that the italic is used here and then the bold is used here. In HTML5 they've sort of gotten away from using the i and the b tags and instead want to use ones that are more indicative of what they actually do. So em instead of i is actually to add emphasis and instead of b for bold they actually want to say we want to make these strong. And so you're going to see both of these in examples, so I wanted to make sure you saw them. If we go back to the website and refresh we're going to get the same formatting. So the i tag as well as the em tag are the same instructions to the browser and that is to use italics for the font and b and strong are also both the same thing. Of course, HTML5 is a hypertext markup language. Now what do we mean by hypertext? One of the basic ways that the web works is that sites can link to other sites, that you can follow this chain of information across from site to site. It's a way the internet works today. And this is using a tag called an anchor tag or an a tag. So for the Github here, let's give them the opportunity to click on the Github and open up the Github website so they know what we mean by the Github website. So inside this a or anchor tag we're going to include a property called href. Href says where should this link go and in this case we'll just go ahead and say Github.com. When we refresh this in the browser the Github now is an active link. When we hover over it we can see it's going to Github and it's displaying differently in the browser so that when we click on it it will go ahead and take us actually to whatever the webpage, whether it's internal to our project or an external webpage, like we did here with Github. The last thing we'll do is go ahead and replace the content of the name of our website in the h1 here with an actual image. So I'm going to replace that and just create an image tag itself. And the image tag is going to want to source to some image to display and in this case I'm going to use a folder structure inside my project and in this case img/logo.gif. So of course our folder here with the index doesn't have any folders. Well let's go ahead and change that. So we now have an image folder that I just created with Sublime. Now you could use any method you want. And I'm going to copy from my resources folder inside of the samples that are available to the Pluralsight plus members, you're going to find a folder called resources. That contains some files including this logo.gif. So we can now see when we open this up there is that logo.gif and so this path is saying go get and display this logo.gif here. What's interesting about the source here is it's going to be relative to wherever this file is. So by saying image/logo.gif, it's going to say, oh the sibling of the index in my folder structure is image and then go find the logo inside of it. We certainly could have also said a full absolute path to a resource as well, but typically if you're using your own resources on your own website you're going to want these to be relative paths, relative to the location you're dealing with. If we go to the browser and refresh we can now see that we have an image that represents the main part of our website inside of just some textual information. So we've seen with just a very simple set of HTML elements we're able to display images, format text, set the title to our element. So we're starting to see that this structure, this document we're creating, that the document is something that the browser is going to render for us based on the instructions that are in the HTML.
-
Tags
Next, let's talk about some important tags in HTML. Earlier I briefly introduced the idea of a tag called a div and a div is just a section of an HTML page. It's sort of a catch all for structural information. So if we take these first two elements and put them in a div, we're saying that these are going to go together somewhere on our page. And this is later going to represent the header of our page. Let's do the same here for the body of our page and let's create a third div that's going to represent the footer of our page. Divs themselves don't have any UI to them unless you tell them to color or add elements and so even though we've added the structural pieces, these divs, in place, our page looks exactly the same. We have a div that surrounds these two elements and another one for the body here and then actually a third one that has no content in it yet for the footer. So let's go ahead and add that content to the footer. I'm going to introduce you to a way of finding special characters. HTML supports this idea of escaping characters and all these start with the and sign. In our case we're going to use a simple one called copy and that's going to show a copyright symbol. And so as it would be appropriate for a footer, I'm going to show just a short copyright notice. These escaped characters are actually what are called entity references in HTML. These allow you to create characters that may not be valid purely inside of the HTML. They are other characters and there are quite a few of these, I'm not going to cover all of them obviously, like gt for greater than and lt for less than. And these are interesting because these represent the symbols of greater than or less than, which of course wouldn't be valid because we need the greater than and less than to represent the delimiters around each of the elements. You can also represent Unicode characters by just representing them as a number. These also start with ampersand, but then are immediately followed by a pound symbol and then a number. In our case if we did, let's say 937, that would be the decimal representation, which shows this character here or after the number sign you can use an x to indicate you're going to give a hexadecimal version and let's do 160 for this character here. And so even if there isn't a special entity reference inside the HTML you can always drop down into Unicode. Normally in HTML this div tag represents a rectangular section of the page, that's why as we're going to use these for headers, footers, and sort of the body of our page, the div is a good solution for that, but sometimes we need to be able to define an inline section of code and we can do that with something called a span. So here I'll add a span inside our text that's going to represent just these three pieces of code and this would allow us later to style or change the look of just the characters that are inside of this span. It represents an inline container much like the div represents a rectangular container. Those are the two basic containers you're going to end up using. But even though in a lot of HTML you're going to see div used to define those divisions or those containers, in HTML5 they introduce what are called somatic tags. And these are tags that are better named to define what they're actually doing. And some search engines can actually look at this information in order to discern what data is inside these tags. As far as formatting, some of the tags are formatted simply as divs, but they're supported as these name tags again that have a semantic meaning. And we'll go ahead and use these here. One of them is the header tag that says here is a section on our page, but I'm going to define it so that everyone knows this is the header of the page. We can do the same down here for footer. Again we're defining a section of the page, but we're also giving it semantic meaning in the markup. This is so people that are parsing it like search engines, mobile devices, mobile and desktop browsers, that they can make some decisions about them, that we aren't implying that the header is going to look a certain way, the footer is going to look a certain way, or the div. But you can imagine a search engine as it looks through might go, well the header information isn't going to be necessarily descriptive of what this site has to offer, certainly the footer may not be, but what's in another section on the page might in fact be more interesting for indexing for searchability. The last of the semantic tags I'll show you, and there's a number of them, again, not going to be able to cover all of them, is just called section. And this is to give more meaning to the structure of a page. If this were a blog engine or something like that we might imagine that this is going to make sense that maybe the body of a blog would be here, the header of the blog and the footer of the blog are here as well. And so that we know that there's going to be some repeatability, it's again providing the semantic or this real world meaning to the sections on a page. So let's show you a few more tags including another of those semantic tags that were added in HTML5, and that's a tag called nav. This is a new tag that represents the navigation of a website and so by certain people looking at this it can know that this is going to be the section that's going to provide navigation across a website. And so inside the nav we can define really in any structure we want a list of links to other pages. We're actually only going to build this one index page, but let's create a couple of links to go to different pages even though we might never implement them in our simple and small example. So here I might have another anchor that goes to the home page. So I might just start it as index.html because that's always going to be the reference to this page itself. Now let's create another one for a contact and I'll just pretend we're going to have a contact page and then finally for about, every website needs those three, right. Three very standard pages. So much like the other links we had created earlier in the browser it's just going to show these as clickable links, obviously contact and about aren't going to take us anywhere because those pages don't exist, but home will continue to take us back to this original HTML page. Before this I'm going to actually introduce a new concept and that's what is called lists. There are two kinds of lists that are pretty common in HTML, an ordered list, which is really a numbered list or an unordered list, which is really a set of bullet points. So let's start with an ordered list. It starts with an ol tag and ends with an n tag, like all of our pieces, and each item in the list is wrapped with a list item tag or an li tag. I'm using a little shortcut here in Sublime, allows me to quickly just surround and create this structure for us. Because it's an ordered list it knows that each of the list items here should be shown with a number sign. In fact if we can look at it, we can now see that it is just a numbered or ordered list. In our case we don't really want an ordered list, we want an unordered list, a UL. Because it's going to be a set of bullet points and later we might change the style depending on how we want this to be shown, but we'll use an unordered list, this is a pretty common case for a navigation pattern. We can see that because it's unordered now it knows to just show bullet points by default. Again, in the next module when we look at CSS we'll see how to change this to make it look like the exact thing you're really looking for. One thing to notice is that this logo up here, we actually have it inside of an h1 tag and an h1 tag or first heading tag usually has some spacing in it. Same for this paragraph tag we have here. Later we're going to design what this header looks like exactly and so this probably isn't useful to include the h1 or the paragraph tag as tags that have some built in formatting to them and so I'm going to go ahead and convert both of those to divs. This won't substantially change the way they look, but will allow us to remove some of that spacing in between them without having to specially format that later. The header is really all the items inside this, currently the section is this whole text that we had created, and then finally we have our footer down here. Don't worry too much about this being a little simple and ugly. We're going to get to changing this design when we get to the second module.
-
HTML Forms
Now let's talk about forms in HTML. So far in the website we've built we're only displaying information. We're showing the logo and some information about the site and some text and a footer, but we're not allowing the user to actually give us any information, to collect information from the user. Let's go ahead and do that using HTML forms. We're going to do this in the section here and right after our paragraph I'm going to create a form element and a form indicates we're collecting some information and then probably submitting it to somebody, whether that's sending it to the server or to some standard service, but we're taking and collecting data from the user so that we can send it back to someplace on a server. In this course we're not going to cover the programming on the server side, so we might use some standard services that are available out there on the internet to just see how this all works. An element that's important to forms is one called the input element. If we go and look at the page with this input element, you'll see that by default the input is a text box. Just a standard old text box. So it's collecting some textual information, name, password, email, search string, whatever you want. But it's just a simple input box. If we create a second one of these we can tell it what type we're actually looking for. Now some of the controls you're going to be dealing with are going to be input with special types. In our case, I'm going to make the type of type called submit and this is going to look like a button and this is the button that's going to say go or start or in our case search because we're going to create a small search form. If we look at this in the browser we can now say that we have that input from the first element and then an actual button that is going to be executed when we press the search. In order for a form to know where to send the data it's collecting, we need to give it an action attribute on the form itself. And for the action, for the purposes of our little sample here, I'm going to use an action called echo. So this is a small tool I have up on azure websites that will take any input from a form and then just show it out on a page so it can see what's being sent. If we run this in the browser and press search, it's actually going to take the contents here and attempt to send them to the action. So you can see here it sent us to the echo page, but it didn't send any data. And the reason it didn't, let's go back, is that it needs to know what to call each piece of data. In the case of an input we need to give it a name like search phrase for an example. And by giving it the name of search phrase we're telling it to, when it sends it to whatever action we want it to send it to, to use that as the name of the value that the user has inputted. Let's refresh so you can see what I mean. If I now say hello and press search, it actually adds it here to the query string. Search phrase equals hello. It knew that because we had an input called search phrase and then the values was whatever was in that input box. So let's use another input here. But in this case we'll use a type called checkbox. And I'm going to give this a name of useStars and later on when we implement this against Githubs repositories we'll see why I'm using a checkbox here. But unlike the search phrase, I want to give it a default value, so I'm going to say checked equals true. This is a property on checkboxes that says please make this checkbox checked by default. I'm also going to add some text here so that we can see what the checkbox is for. Use stars? And then I'm going to introduce a new element called a break or a br tag. Br is always self closed in this way and it's just a single element, but the br here will cause each of these to be on their own line. This causes a line break inside of the formatting of the HTML. So if we go look at this in the browser we can now see we have the text box still there, but now we have a checkbox by default and if we go ahead and search we'll see we're now getting both of those elements. Search phrase has its own because it's named and then use stars is now on or true for the checkbox. The last piece we're going to add here is going to be a dropdown or what's called in HTML a select. A select allows you to have multiple options for different options that can be chosen. Let's go ahead and give it a name and call it lang choice and the option elements inside the select can have an attribute called selected. Now you can say selected equals true, but this is another peculiarity in HTML in that sometimes the attributes existence is enough and in the case of selected that's true. Option selected means that all is going to be the selected item by default. Now the first one is going to be the selected item by default anyway so we don't really need it there, but we could decide to, as the default, make C# the selected language. And let's go ahead and put a br tag here and now let's go ahead and look at this in the browser. So now we have a drop down and even though it's the middle option it's still the default selected one. As I change this value you can see that it's going to pick whatever is there as well. And if we search, because we've named it as lang choice, it'll show up here as one of the properties as well. Now the way that http works is you can send things in a variety of ways. Doing a get is a way that most of the web works. I type in google.com, it does a get to google.com and then they return me an HTML page, much like when I do a get in the browser for index.html, this page actually is returned. In the case of forms, often you don't want to use the verb of get, you want to use the verb of post. Post has the idea of creating new data. It's essentially the insert or the update of data across the web, must like you might think in standard data access terms. So in the form we can actually specify which of those verbs are used. We do this by using another attribute called method. By default the method is get, but if we change this to a post and just execute our same page again, we're going to see that it posts to this echo URL just like we saw before, but instead of attaching it as the query string it's actually posting it as the body and this becomes important because some types of data aren't able to be part of a query string. The query string semantics after the address here, the question mark query string implies that we can only have textual information, so if you need to send up an image you chose or some other structural data, it'd be difficult here. The way it does this is it actually sends it as the body of the request, sends it as something called form encoded as a format. Form does this by default as just a list of the properties inside the form. Knowing how to change these and knowing that the form object itself is going to handle that is important to know when you're doing web development. Later on in the course when we talk about JavaScript we'll be able to see a little bit more behind the scenes how the actual networking is happening, but for now understand that you can specify the method when you go ahead and define a form. Let's do one more thing with forms. In our form we just have the input where we're collecting data, but we don't really have a place for us to show what each of those pieces of data actually represents. In fact, here in the form we have use stars next to the checkbox, but we don't know that hello is really the search string or that this is specifying some language. We don't have a way to really describe that. We could literally just say search there and say language here and get something that approximately looks like what we want. But more interestingly you can specify a new element called the label. Now the label is going to allow us to say search phrase like we did a minute ago, but we're going to be able to point it at a specific input. This becomes really obvious when we're doing it for the checkbox. So let's go down to the checkbox for a minute and let's surround this with a label and we're going to say for equals use stars. Now this label is coming after the checkbox, how does it know which one it's for? That's why the for attribute is there, it's to tie the two together. As you layout these pages the label may not always be before or right after some input and so the for ties them together. Unfortunately in HTML the tying together isn't as simple as it looks because the for attribute expects that this name is going to be a new attribute on each of the inputs called id. The name attribute is used within forms to define what data to send, but id is used within HTML to define the unique identifier for an individual element in the document. And so here we're actually going to repeat it and this is something you're going to see very commonly done in forms. I wish that they would fix this so we didn't have to do this over and over again, I'm sure someone smarter than I can explain why we have to have these, but we have to have these. So let me go ahead and create a label for the language as well. So you can finally see why this is important. If we go look at this in the browser, we're going to have the same look we had a minute ago, but what happens with the for is it actually gives some additional functionality to your form. When I click on the label it's actually going to take me to the control that's important here and for input controls and drop downs it's not all that interesting, but it's crucial here. This means that when I click on the label for my checkbox, instead of having to feebly go look for just a tiny search area for the checkbox, it's going to check or uncheck the box for me. One of my biggest pet peeves with HTML pages out there is this very simple built in functionality that every HTML page should be doing when they're using a form, simply isn't there and it makes me a little crazy. By adding labels we're giving some semantic support for knowing what parts of the page belong to other parts of the page. And this is really going to eventually, once we make our pages look the way we want, it will enable us to richly format the pages with CSS in our next module. But that's essentially a core of how forms work. We're going to come back to forms when we talk about JavaScript where we'll interact with it a bit more, but at least we can see how we can build up a simple form on a page.
-
Cross Browser HTML
Next let's wrap up some HTML ideas that are going to allow us to handle cross browser HTML a little bit better. Before we talk about cross browser, let's talk about one more sort of pseudo tag that's going to be important for you and that is the comment structure inside of HTML. The comment structures starts with an exclamation point or bang if you prefer and then two dashes and then it always ends with two dashes and another end tag. Anything inside of this, even multiple lines, are going to be comments. It's completely ignored by the parsers. This is going to give you a place where you can actually add comments inside your HTML that are for the most part ignored. But sometimes you'll see comments at the top here to define some information. Again, it's ignored by pretty much everyone, but it could be useful for you to add comments. One of the places where comments become sort of interesting is a structure that's out there for adding cross browser tests. So in our case we can actually say if the browser I'm using is IE and it's less than 9, so this is essentially saying if less than IE 9, so IE 8, 7, 6, 5, whatever is, we want to do something here. And we're using the commenting system so that we can put optional pieces of code here for older browsers. Again, the structure is a comment that starts and ends, but it also has this if browser version, less than, you could do gt for greater than as well, and then it looks for an end if afterwards to be sort of the end of this block and then here we could do whatever we want. We could say… Now this all gets downloaded and consumed by the browser and only certain browsers that test these things will include whatever is in between these two blocks with something special for these cross browsers. For example, there's a script out there that will handle HTML5 tags for older browsers and this really only effects IE browsers before 9, which is why we're using that there. And so we can add this script and I'll show you how script tags work a little later, but essentially we're saying go get this HTML piece of JavaScript only in the case that we're using an older browser. Otherwise the headers and the sections and the navs will all be interpreted correctly if you're using IE 9, IE 10 or IE 11. If you're using an older version the script actually goes through and rewrites them to straight out div tags so that the browser knows what to do with them, otherwise they might be ignored by older browser. And the magic here is if you are using an older browser that doesn't know about this, let's say you're using an ancient version of the Android browser or let's say an old Safari browser, because this is just a comment, it still adheres to the comment rules, this will just be completely ignored. So it's only the browsers that will actually use it. And this is going to allow us to include some code, it may be CSS, it may be JavaScript, it may be some inline properties that are important, that are specific to specific versions of browsers. You're going to see this in a lot of templates and a lot of examples and this is in fact one of the lines of code that goes in every web project I do. So it ends up just becoming boiler plate background, but understanding what it looks like and what it does I think is important for most beginner web developers. Let's wrap up this module.
-
Summary
So we've been talking about HTML primarily and focusing on some HTML5 specific features. But you should really just be thinking of this module as being one about markup. When we look back at the history of HTML it's important to understand that the nature, in some cases the peculiarity, of HTML has been because it's always been written by the people who release browsers. The browser makers end up being the ones that write the specs and they sometimes write them in the reverse order, unlike most computing systems where you'll write a spec and then you build the software, often the software is built and then the spec is written to match the existing base of users out there. It's easy for new web developers to get a little scared by everything that encompasses that HTML5 moniker. It has really become a catchall for a variety of web technologies. When we talk about HTML or specifically HTML5, let's really focus on the ML part of HTML, the markup language part of it and understanding all the different tags that you may and should be using in your projects. We've only touched at sort of this surface area of them including forms and structure and header tags and the basic structural information about HTML, but as you build websites you're going to find the use and the need for more and more tags and you'll be exposed to them as you need them. Remember that HTML really is just structure. It's just a hierarchical document that displays what the browser should be showing to the user. All that the HTML becomes is an object graph in memory. So don't get too confused by the nature of HTML. If you think, as a developer, that it's only going to be an object graph, that we're just creating parent child relationships, a true hierarchy, I think you'll find it's pretty easy to wrap your head around. We've spent a lot of time on creating forms in HTML and this is really the key to accepting input. So whether those are buttons and input boxes and drop downs and radio buttons, which we didn't really show you, or checkboxes or simple textual input, these are all part of the form elements inside of HTML. We also showed you a simple technique for bringing in assets like code and CSS or other things that are going to be specific to certain browsers so that you can fix cross browser issues when you need to. It's becoming rare that you need to, but it's something that you certainly want to keep your head around and we've shown you some simple techniques for how to do that. This has been the HTML5 module. My name is Shawn Wildermuth of Wilder Minds. Thanks for joining me.
-
Styling Your HTML
Introduction
Next we're going to talk about how to style your HTML. My name is Shawn Wildermuth of Wilder Minds. We'll start by talking about styles in HTML and then we'll introduce cascading style sheets. We'll walk through CSS rules, CSS selectors, sizing in CSS, positioning in CSS, and finally how to debug styling in the browser. Let's get started.
-
Styling in HTML
Let's start out by talking about styling in HTML. There's a style property on every element inside the HTML and the style property allows you to specify rules for layout. We can certainly use this style property, but in most cases we want to separate the UI and that style. We can do this by creating style tags in the header and including the style information. This would keep it separate from HTML, but this really is only separating it on a per page basis. Instead of that, we're going to use a technology called cascading style sheets or CSS for short. These contain all the rules for styling for the UI, leaves the HTML for structural information, and then this way you can allow for site-wide rules, not just page specific rules and overriding for specific cases where you need elements on specific pages to override the default site-wide rules. Let's start out by looking at the style attribute and how that works. Over here in our index.html that we built in the first module, we're going to see different elements on the page. If I come over here to our header element, which just to remind you looks like this, the header element is the section that contains the logo as well as the site description in the list of nav instructions for the home, contact, and about pages. Because the header, like every other element, has a style property, we can simply use a set of name value pairs here to change the way this looks. So in this case I'm going to say background color, which is one of the supported style names, and there's a lot of them, we'll cover a few in the course, but over time you'll learn more and more of these. I'm going to set it to light gray. Now the way the name value pairs work in styling is the name of the property, in this case background color, followed by a colon and then it's value. And then a semicolon separates it from the next name value pair set. We save this and show it in the browser. We'll see now that that header section has a light gray background. When we talk about the style property, this is really what it does is it changes the look and the feel of that object and because the other objects live inside of it they are also changed by it. In this case the header tag itself has a background of light gray and because none of the other elements have styles to specify the background color, the light gray shows through, whereas if the logo or one of the other parts of the page had its own background color that would show around that part of the element only. But of course creating the styles on each element individually is really mixing the structural UI information from the way it's displayed on a page and we want to separate that and we'll do that next.
-
Style Sheets
So now let's talk about the style tag that is usually put in the head element. Up here in the head we can add a new section or element called style. And this is going to allow us to put styling information that's separated from the individual attributes. So in our case we want to take the existing style information we have here and we want to put it in the style section. The problem is we need a way to specify what element it belongs to and in this case we can just say header and then create curly braces around the set of properties we're going to include. By doing this we're going to get the same behavior we got by including the style element. It's going to be the instructions for styling all the elements on the page with the name of header. Of course we only have one, so it's only going to affect our one style. We refresh it and we can see that it still looks the same. This whole section is called a rule or a styling rule. And this is typically going to match one or more elements on a page and then specify how those should be formatted. We can add multiple properties here so we can describe all the different ways we want to change the look and feel of that element. In our case we can go ahead and set a border property. And inside of a rule not all of these individual declarations or name value pairs are going to be single valued. We can see the background color has a single value and that is light gray, but border has a number of elements to it. We're going to say it's going to be a solid border that is 1 pixel wide and is going to be black. So in this way it's a compound set of values. We can say all the information about it in individual border and in many cases these can be broken up onto individual lines as well, but this usually is a bit more efficient and will make sense more to you as we go along. If we look at this now, we'll see that we now have a black border around our entire header section. Let's create another rule and this time it's going to be for body. And of course boy is going to specify it for the entire UI part of our page, everything that's within the body section. One of the properties we can specify is font family. This is going to be the name of the font that can be used, but of course on different machines different fonts are going to be available so font family supports fall back. So in our case we're saying if Segoe UI exists use it, otherwise fall back to Arial. If that doesn't exist either fall back to Helvetica. And if none of those exist fall back to any sans-serif font you can find. And this way depending on machine this may render a little bit differently. We're specifying font names that we expect to exist on the resulting machines. You can of course import and use fonts and use those specific fonts that are downloaded, but we're not really going to cover it in this simple styling example. Another property we can specify is font size. But in this case we've said everything inside the body we're now going to change the standard font family and the standard font size. So this is going to take our example from this with a lot of serif fonts I'm going to take it down to this with a lot of sans-serif fonts. Now this machine happens to have that UI font on it, so it's actually using that one, but if it couldn't find it it would again drop down into Arial or Helvetica or any sans-serif font it could find if you find a machine without any of those major fonts on them. Let's go back to our header and let's change the font family here and let's just specify Times New Roman and serif. So we'll use Times New Roman if we can find it, otherwise just use a serif font. Now we specified font family in two different places and how does it know which wins? Let's look and see what the UI tells us about which wins. The header won the fight for who is going to actually use it and the reason is that CSS and the styling stack on the web is using a set of rules of cascading these properties. Because body is specifying the body of the entire page, the more specific tag of header is going to win in this case. So there are two rules about cascading you want to think about, one is if a rule occurs later in a list of rules it will win over an earlier rule and that more specific rules beat less specific rules. In our case body being the generic for every element on this page looses out to the more specific header rule that specifies what it is for just the section in here. We're going to see some more of this overriding or cascading as it's known as we go through some of the other examples.
-
Introducing CSS
So now that you've seen a couple of the pieces in action and working, lets talk about CSS itself, the actual cascading style sheets. The style tags on the top of the page certainly work, but they aren't very reusable. I would have to copy this onto each and every page of my project in order to get them to work across the project and of course maintaining them over time is going to be a problem and so in most cases instead of including style information anywhere in the HTML page we're going to separate it out into a new file. So I'm going to create a new file and a new subdirectory called CSS and I'll just call it site.css. Ordinarily you're going to keep your CSS segregated together so that you may have a number of CSS files, some that are specific to the entire site, some that are specific to certain pages. In our case we'll go ahead and create the site CSS that we'll use for each page. In CSS it uses the old c style comment tag so I would just like to put the name at the top of it, that way we know what file we're looking at if it's open in an editor. And all we have to do for the syntax is use the same syntax we get from the style tag. So I'm going to go ahead and cut and paste that over into our CSS file. And the trick here is instead of having a style tag here we're actually going to include the style to be downloaded and used on the page using a link tag. So we'll just create a link and there are two properties that we need to set, one is rel and that's going to tell it what kind of link and in this case it's going to be a style sheet rel. There are a couple of other rel tags that can be used here, but since we're focusing on styling this is what needs to be in the link for to download a style sheet. And there's an href tag that represents the actual path to it. Since our HTML page is here, our site CSS is in a subdirectory called CSS, we can just say css.sitecss and it will download that. Now that we have both files created and saved, let's show you that it's going to show the same data in the browser. So we're still downloading this page, but we're downloading the additional CSS file to style our page for us. We can see that this actually works, but lets comment out this line so that we can see our header go back to the new style sans-serif font. So it's pulling in the CSS information directly from our new CSS file that we just created. So let's make some more changes and teach you a little bit more about the syntax. In here let me create a new rule for that footer tag that we're using. We could certainly go ahead and copy this style into the footer and that would work. We can now see the footer is gray and surrounded with black, but this is duplicative. We have the same properties in two places and instead of doing that we can actually use a comma and say these are the rules that apply to both the header and the footer. And in that case we then no longer need this style and we can just pick which of the items here apply to both the header and the footer. So this is now a rule for both. The trick here is that this rule is for everything that applies to both. We can still have a separate rule that only applies to one or the other to have properties that aren't common. So in this case we'll introduce two more properties, padding, which is how much room from the side of the element to the element. So I'm going to give it a little bit more room to put some space between the text and the side of the element and border radius, which is going to allow us to round the corners of our border. In this case, I'll put a little circle around the corners on just the foot as well as add this padding. If we go back to the website we can see now there's more space in here and the corners are just a little rounded. So the rules still apply for header and footer for the background and the border, we've just added some other properties that are specific to just the border. And you'll see that this is not uncommon inside of writing your CSS style sheets. You're going to see that there are going to be some cases where you can batch together or reuse without duplication one rule as it applies to a number of elements and then have exceptional cases. So what ends up happening at the end of the day is that the footer element gets both these properties and these properties. So CSS reads all the rules and then figures out what properties apply to each element by just doing the logic. So know we've talked about named elements, like header or footer, body, etc. Let's show you some new ways to indicate what elements you're going to style.
-
ID Selectors
Now let's talk about selectors based on the idea of an element. When we look at an individual rule, let's take the body for instance, the part before the curly braces is called the selector. The selector syntax is what decides what the rules are going to be applied to. So far all we've done is use the name of an element. But we can also use a new property I'm going to introduce called id. So let's take our section here and say id equals main. So we're going to identify this section as main. This way if we have other section elements we can really specify that it's only for this one instance. Id specifies a single instance inside of an entire HTML page. It needs to resolve to a single element on a page. In order to style it we use the pound and then the name, in this case main, to specify the selector for that element. And in our case we're going to take that main section and change some of the properties. So first let's set up a border like we've done before, so it'll be a solid border again 1 pixel, but instead of picking a named color like black or light gray, let's go ahead and use a pound syntax and when you start a color with a pound it's going to indicate the red, blue, green values for the color. This way you have a fuller pallet of colors you can choose from. After the pound value there can be either three 2 digit hexadecimal numbers or three 1 digit hexadecimals numbers and these will specify what the exact color is. In our case we can say ccc, again these values are going to be red, green, and blue, and it will pick a color based on that. In this case because they're hexadecimal numbers this is going to be a fairly light gray as well. We're also going to pick a border radius to round those corners. Another property we can use is called color. Color is going to specify the color of the actual text inside this element. Now because our background is going to be white, unlike the header and the footer, we probably want a color that's going to show up pretty well. By default so far it's been black, but I like to make things a little lighter than that so I'm going to specify another pound value and just say 202020 as a dark color, again, all zeros will result in a pure black, all FFFFFF, which is 255255255, for each of the red, blue, and green values will result in white. So having a red, green, blue that are all the same is going to give you a color that is some black and some white, in this case it'll be a fairly dark gray. Let's look at this in the browser. So we can see we now have a fairly light border around it and that the text over here is just a tiny bit lighter than the black we see up here. It's actually a little hard to see. Let's make a quick change so we can see it a little better. If we change this to FF0000 that's actually going to be pure red, FF indicating that a hexadecimal number of 255 for red and then no values for green or blue. In that same way we could do the same for a mix of green and blue, but in our case we'll go ahead and return back to that dark gray color as that will look best for our design. Of course our problem here is that we're stuck next to the header and the footer so we can't really see the border very effectively. So let's go ahead and add a margin and this is going to be the space between our element including the border and the edges of the next element. This can take the form of a single number like 5 pixels and in that case it will bring the entire element in 5 pixels from the top, the bottom, the left and the right. Instead of specifying one value we can pick individual numbers for each of those values by specifying four numbers. The way this works, in CSS all these numbered values start with the top, go to the right, go to the bottom, and then go to the left. It's going clockwise around the circle of values and it always starts with the top. So we can see now that the top is 5, the right is 10, the bottom is 5, and then there's 0 at the left hand side. In our case I actually want the top and bottom to be about 20, but I want the left and the right to be zero and in fact for zero pixels we can just say zero. So that's about the look I want, I want a little space between the header and the footer for us. But because this is duplicative I can actually also give it two values. And in the two value form the first value will indicate the top and bottom and the second value will be the left and the right. So that shouldn't change the way it looks because that's in fact what we're looking for, we're looking for an example of where the margin is 20 top and bottom and then zero left and right. And lastly, we want some space between our text and the body of the element, so let's go ahead and give it a small amount of padding. Padding uses the same rules in the that it can be one, two, or four values here, in fact three is supported as well, but we won't really talk about that. But in our case I just want 5 pixels to just separate us from the rest of the element. Now we can see this is starting to look a little bit more like what we want it to.
-
Relative Selectors
Next, let's talk about relative selectors. Back on our page, we have the main element that we had specified the id for and we also have a form element that's inside of it an then inside of it are a number of labels. Now we could go ahead and specify id's for all the labels so that we could then say search label and then create another one for lang label, et cetera. But using id's for everything can get a little laborious, especially if there's some commonality like there is with the forms. So one way we can do this is to use a selector that is positional. So we can say that we want to style the things that are a main and then use the greater than to say style things in main who are a child called form or also a child called label. Again, this is mimicking this hierarchy here. Main, form, label. Let's go ahead and put font-weight, which is another property we haven't talked about, but let's go ahead and make it bold so that all the labels are going to now be bold. So that matches it, but it's not actually a necessary. Using these greater than symbols can be a bit fragile because of course what were to happen in the HTML if we were to add another layer here, maybe we put this in it's own div or we moved it into another part of the main section. Having that direct walk down the dom hierarchy would be a bit fragile and so the solution there is to actually say hey in our case we're going to specify that any label, anywhere inside of the main tag, we're going to specify with this set of rules. Now this may look similar to what we did here for header and footer, but this comma is so important. This comma indicates it's a separator between selectors and that the rules apply to all the selectors in the heading here. Whereas down here without that comma we're seeing label that lives somewhere inside this main element. Let's do the same thing for the input element. Let's do main input and let's specify it's width at 150. This is another property we haven't talked about, but unsurprisingly probably to you there's a property called width where we can specify how wide these individual elements are. And this will match anything that is an input element. So the search phrase, the use stars, and the lang choice. If we look now in the browser we're going to see that this search phrase is now this wide, but so is the checkbox which just looks weird. You don't really want both of them to be that wide and the select here wasn't included in that width. So how do we address that? We address that by being more specific. So here like we did earlier we can include multiple types, like let's go ahead and put our select in here as well, So all of the inputs and all the selects inside of our main will be 150 pixels wide. So now that's a little better, but we still have this really wide checkbox. How do we tell it not to use the checkbox? If you remember I told you that rules are matched by specificity, how specific it is, and so if we look at our inputs we have a type declaration here for checkbox. It's easy to have a negative match and in fact in most cases you're not going to want to do that, so instead of doing that let's go ahead and put the type of text here, that way we can actually match input that are text make them this wide as well as selects and make them this wide. So we change that, we can say type equals text and now we'll only match for the search phrase and the language, but leave our checkbox alone. In many cases we might have a number of these in here like main input type equals password and even main text area because those are all input types that need to usually look in a form to be about the same width. And so we accomplish that by using multiple selectors with one set of properties that define them. So if we go back to the index at HTML, the only other one we want to really look at is this type submit because we've now only specified the input types we're going to change the width of, we might want to include a new rule for the submit button itself. And in this case we'll use a number of properties that we've seen already to change the look of the submit button to something more pleasing than a square gray box. We now have a search button that looks a little more slick. So next, let's talk about a selector that can match an arbitrary number of elements.
-
Class Selectors
So now let's talk about class selectors. Back in our HTML we've got an image here that contains our logo. We can set a new property on that called class and the idea behind class is a named matching for some styling rules. It can be used for some other things, but they're mostly for styling rules. And in this way we can arbitrarily attach a class that's going to match formatting instructions. So let's call this class bordered image. So we want to set up a rule inside of our site CSS that says if an element has the class of bordered image let's go ahead and give it a border. Let's drop it in up here for no apparent reason, bordered image, and the way that the selector for classes works is it starts with a period and then the name of the class. In this case I'll say border solid 1 pixel and let's make it a fairly dark gray. Let's go ahead and give it a border radius 2 while we're at it. If we look at this in the browser, we can now see that it has a border because we've applied this border to the bordered image. Now we're not specifying that this class has to only be against the image, we've only it named it that. If we came down here into the index.html for the form and we applied the same class, even though it's called bordered image, probably a bad name in this case. We should now see that same border around the entire form. So you can think about this as ways to take simple UI decisions, like adding a border, centering, formatting, specifying a font, those sorts of things, as classes of elements. And in this case we're specifying that a class has a border and we can apply it to whichever element on the page makes sense to have those sets of attributes. It's all additive, so in the case of the form we still have a form rule here that added additional attributes. This class would be added to the specific properties for the element. So we will get a set of properties that is an and operation against all those properties. In this same way we can have a class, in our case we'll call it simple form, that applies to the form so that we can do the formatting for our form elements that are based on the forms class instead of its location inside of the main. So let's assume that in our style sheet instead of us wanting all the labels and sizes of the inputs and even the color of the submit button to be based on whether it was inside the main element we could do the same thing here with simple form. It's still based on that same formula, labels inside of the element that's labeled with the class simple form in the text input inside of simple form, the submit button is inside of simple forms, etc. So it works in the same way, we're just specifying that the container above these inputs and labels selects and text areas is going to have the class of simple form. And this is useful especially in forms when you have maybe two or three different styles of forms across your webpage. One thing that might not be super obvious, but I'll make it obvious here, is that a class can be multi-valued. In this case we have bordered image as a class as well as simple form as a class. This does not have to be a single valued property. It will take all the classes that it matches and include all of them in the styling for that element in this case the form. Because we've done this we can also add a simple form set of attributes for the form itself. So in this case let's go ahead and add a padding that is specific to the simple form, not specific to the bordered image class we used before. And we'll now see the form has a little space between it and the edge of the form itself. That padding says that all my children are going to be spaced a little bit inside of myself. I'm going to give myself in essence an inner margin if you want to think about that way. We will notice that the form here now has a mix, it has the border and rounded corners from the bordered image class as well as the padding from the simple form class. So you can really separate your individual rules based on the functionality they're going to provide to the rendering mechanism.
-
Sizing and the Box Model
So let's talk a little bit about sizing in CSS. We've introduced some different properties, like width and you can probably assume that there's also a height, padding, and margin, and border all make up some part of the sizing story. But I think it's important you understand the CSS box model so that as you're putting these together you understand where your actual height and width are coming from. It also starts with your content. Your content is inside of what is called the padding. The padding is inside the border. And the border is inside the margin. There's also a left, a right, a top, and a bottom that can also be specified to move it around the page and we'll show you some examples of that in a little bit. The height you specify is really the height of the content alone, not as it relates to adding the border, the padding, the margin, and then whether it's top, left, right, or bottom. The width is done the same way. It's for the content alone. There are two more properties, actual width and actual height, that can be read at runtime and we'll see how to do that a little later, but this represents the actual width and the actual height including the margin, the border, and the padding. So there is a disconnect between the way they handle height and width of the content and actual height and width, which are going to include these other elements. So if you need something to be exactly 200 wide you have to make sure that your width plus your padding plus your border and plus your margin are going to equal 200. By specifying the content of 200 and the padding of 5, the border of 1, and the margin of 5 you're going to end up with something that is 200 plus 5 plus 1 plus 5 or 211 wide for your actual width. Let's see this in practice. So if we go back to our simple form here, let's go ahead and add a width to it. Let's say a width of 300. We can now see that the width of the form is this wide, but the width of the content of the form is going to be 300 wide, but by adding the padding here and the border it's actually going to be 306 wide. The reason is we have a padding of 2 and a border of 1, so that's 300 plus 2 twice, once for the left and once for the right, and then the border of 1 twice, which is another 2, that makes 306 and so you're going to have to take all these different properties, margin, border, and padding into account when you're going to specify the size of an element. If it needs to be an exact size that can be an issue. And we'll come back to this exact size in just a minute. Now let's talk about a common approach of actually wrapping all these pieces so that they aren't the width of our page. You've probably noticed that most websites out there are actually centered on the page and let me show you how that works. If we come here into the HTML and I'm going to collapse these three sections so we can see them all on a page and I'm going to wrap these in a new div. We can now see that this div is now going to contain all three sections. Let's go ahead and give this div a class called container. Now let's create that container class rule. Container, like we've seen before, but in this case we're going to specify a standard width and I'm going to use 989 pixels. This is a pretty common width that works well on all monitor sizes. This really accounts for all of your content to be contained on a monitor, 1024 x 768 and then it's just centered in all monitors that are larger than that. When you're dealing with mobile sized browsers, this is a little different and if you view the Pluralsight course on mobile web development you'll see some techniques there for dealing with different screen sizes, but for now we're just going to go ahead and pick container as 989. So far in the course I've actually had our webpage zoomed in so we could see things a little better, but let's go back to 100% magnification and we can now see that the whole page is this size, but we'd like to be able to center it in some way and so there's a little trick here. We could say text align center, but that's actually not going to center the div, it's going to just center text. Instead we're going to use margin. Margin has another value we haven't talked about and that is auto. If you remember when I said that multi-valued margin and padding can both take one, two, or four values. In our case we don't want any margin on the top or the bottom so we give it a zero for the top and the bottom, but for the left and the right we're going to tell it to use a margin of auto. This is a special value that says make the margins the same, but in essence center them. So when we specify margin of zero in auto here, the container itself, and again the container can't be seen, it's just blank at this point, is going to center this. Remember the container is 989 wide and by pushing a margin of auto the two sides here get equal sized so it ends up looking centered. Now we're starting to look a little bit like a lot of sites you've seen that are using the same technique. Next, let's give the container a background color and in our case let's go ahead and pick dark gray. So when we say dark gray what we're actually getting is just the container itself is going to be a dark grya, and so all the elements here that don't have a specific background color, in that case our body here, are showing through. Of course the header and the footer, which we specified a color for, are going to show theirs on top of that light gray. Instead we're going to go ahead and specify a background of white because soon we're going to make the margins or outside of the container a different color instead. Lastly, we're going to add a padding here so that there's some space between our container and our other elements. So now let's go back to that body tag and add that color. Let's say blue just to add a little color to our lives. Now that when see this we'll see that there's blue everywhere, it's actually kind of a difficult blue. And let's go ahead and say dark green and here in the browser we can see it's that dark green that sort of matches the other greens that we're working with on our page, so it mostly works. But we do have this little space on the top that I don't care for. And so how do we tell it that this container should be against the edges? The reason this is the case is that the HTML and the body both have their own margin and padding that aren't zero by default. So we have to add that. We can do that with a combined tag to say HTML and body padding zero, margin zero and that will in essence reset it. So it's now up against the edges where possible. In fact, many cases the starting point for your CSS are going to be those resets for body HTML as well as maybe some other standard CSS that you use project on project. So let's talk about position next.
-
Positioning in CSS
So we've talked about sizing, let's talk about positioning in CSS. If we take a look at our CSS and let's go to that simple form that we have on the page, we can see that there is a property called position and by default this is static and static essentially says please draw me in the order of the hierarchy, top to bottom, outer to inner. So it's going to naturally flow the hierarchy onto the page. By changing this you can decide to position things in a couple of different ways. Let's change this to fixed. We can now see that the search form is here where we had it before, but it's not taking any height or width because we're telling it that we want it to be fixed on a page in a very specific position. And in this case it's still going to be drawn in the same place in the hierarchy, we're just telling it that it has to be in this exact place. Fix simply means fixed in this position, but still relative to the hierarchy. If we change this to absolute we're actually telling it we want absolute positioning on the page. Now this is something you should use very sparingly. Some of you may be listening to this and go, well I've done Windows development or I've done Mac development and I can absolutely position things exactly where I want them. This tends to break the web a little, but there are occasions where absolute positioning, like a floating piece over your website, can be pretty useful. And in these cases we need to specify top, left, right, or bottom to specify that. So if I say top equals 5 pixels and let's say left 5 pixels, this will be positioned exactly 5 from the left and 5 from the top of the entire window. In the same way if we did bottom and right we're going to get the same behavior, but for something that may float on the bottom right of the page. Again, using this sparingly is useful, but for things that you want to float over the page that don't flow with the page, this can be pretty useful. Of course, for us we don't need these so I'll just comment them out so that if you have access to the source code you can at least see what they were. Let's talk about how things are displayed or laid out on the page next.
-
Display in CSS
So let's talk about the display property now. Back in our HTML let's create a new element that's right after this form, a new div and let's call it results. This will be where the results of our search will ultimately end up. If we look at these in the browser this will, by default, put this below the element before it. It's not going to flow it to the right, it's going to flow it to the bottom and let's talk about why that is. In the case of forms and divs they're actually, by default, have a property called display of block. So in our case when we look at the different elements in HTML there are some elements that are block and some that are inline and some that are called inline block and there are a few other display properties, but those are the three that I want you to sort of focus on, block, inline, and inline block. So in our case what we'd like to do is take this whole section here and put it to the right so that our results are to the right of the search pane. We can do that with a little CSS. Now we've already made the width of the simple form a fixed size, so let's go ahead and it's not right next to it, but make sure it's nearby so we can look at both of them at the same time. And let's go ahead and add a padding of 2 and let's give it a width of let's say 600 for now. And over in the HTML I'm just going to give it a class just like we did our form of bordered image. Though, again, having the image on the back of this probably wasn't the greatest idea and we can always fix that later. So at this point it should look like this. We have our box, we have it 600 wide and 300 plus 600 should fit here, right? But because these are both block level elements they're defined as block and block means that they're going to top to bottom stacked unless we do something different. The way to do something different is actually to change its display and in our case we'll change it to inline so we you can see what the inline display looks like. Now because we used inline it attempted to make it as small as possible and didn't really solve it. It made each of the lines stil where they were and then dropped this new element next to it just to the left and that's because inline is more like the way we put inline pieces in text. That's what inline is for, for the way that we flow elements within let's say a textual representation. Much like this anchor tag here that we have is inline with the text, that is an inline displayed element by default, an anchor tag. Instead what we want is incline block. So we want it to act like a block, which means mostly adhering to its width, treating it like a rectangular element, but we still want them to be displayed inline if possible. By doing this, both the elements are put left to right and if we had three that all fit they would show, otherwise they would wrap onto an individual line. Let me show you that. If this was too long, let's say 700 because of course 700 plus 300 plus the associated padding and all that is greater than our 898 pixel width, it would just fall into the next line. So inline block is like the way that text works in that it'll allow line wrapping and such of elements. And so when you see something like the Netflix que where you have a bunch of little boxes that are all left to right and then they wrap onto next lines and next lines, those are most likely inline block elements. But of course our problem with just the ones that fit here is it isn't aligned correctly because by default there's also another property called vertical align. This aligns things vertically and by default these two elements are not aligned to their tops so we have to add that. So by aligning both elements to the top it now does what we want. Eventually this will have a lot more information and the search pane will always be at the top aligned with what the results are, those results may be fairly tall once we get into pulling actual data from Github. There's another way of putting things next to each other that flow in a different way. We'll talk about that next when we talk about float.
-
Float in CSS
So now let's talk about the float property in CSS. If we look at our page here, if you remember we have this navigation element that has three different links for the pages and what we might want to do is actually put these over here on the upper right hand corner of our page and we can do this with float. We'll introduce a couple of other pieces while we go at it, but the primary idea here is to investigate and understand float. If we look at the HTML for this we have a nav element that then has an unordered list and list items in it, which you probably remember from which we built it earlier. So let's start down here by creating a header nav rule and this way we can have a separate set of rules for the nav element that we might have in the footer later. We could do this if we wanted to format all the navs the same, but in our case I'm going to leave it as header navs so any nav element inside the header element. And I'm just going to say float right. Now float has a couple of valid values, right and left are the two that are most likely used. So let's go ahead and say right in this case. And we can now see that the elements are now floated to the right, the entire nav element is floated to the right, but of course now that it's being floated, it's no longer taking up space in our header. So one of the tricks here with float is to change the order of the elements. If we come here and take our nav element and put it before the others that way it starts at the top of the header value, it'll now take space over here on the right hand side, but we'd really like these to be displayed next to each other so that if we have three or four or five they'll just sort of sit on the right upper hand corner of the page, much like you'll see in a lot of pages. To accomplish this we'll need a new rule just for the LI or the list items. Now we could certainly have put in ul li to be very specific, but in our case we just want to permit all the list items in the same way. Much like we saw display being used before, let's use it again, but say that we want all of these items to be inline. So instead of them stacked block, which is the way that list items normally are listed, we're going to tell it to stack them next to each other. So now we're seeing them left to right, floated all the way to the right of the element, and so let's go and add a quick margin right of about 5 pixels just to keep it off the edge of the page. Now what's interesting about this is you haven't seen this syntax before and that is margin-right when you just want to override one of the margins or one of the paddings you can actually specify the cardinal location, in this case right, as an individual property. So here we're just going to push it a bit from the right and lastly we'll make it a bit smaller. And then this way we've used float to really decide where it's going to be on a page. One thing you'll notice is that the float is stacking things either on the left or the right hand side. So you have multiple things floated, they're going to stack in that order from left to right or right to left depending on whether you're using float right or left. But float doesn't account for space. Float isn't used to compute the size of the container, so you have to make sure that whatever you're floating is going to exist in that container and be correct. You may even have to size the container to be large enough to hold the content because the browsers themselves aren't going to resize the container for anything that is floated. The last thing we'll do is style the links. Now here these, even though the text is all black, are colored purple for visited pages and then blue for unvisited pages. That's because these anchor tags and even this one in Github are formatted special using their own rules. So if we come back up to the CSS, we can actually format these by saying anchor, which is the a tag and let's say color equals green to match our theme. If we refresh it we'll see that we now have green for all our anchor tags. Now that we've formatted them as green we've lost the ability to specify whether they've been visited or not, but most sites no longer worry about that, they'll just color the anchor tags to fit the theme of their project and then they may remove or add the underline where possible. You do want to have some indication that these are special and clickable. It may not be simply that it's an underline, it may be a bolding or an italic or as you hover over something it may change the look, all those are possible with CSS. But now we have a site that has been styled pretty much in the way we want. Let's next talk about how to debug these using some of the browser tools because there's going to be times when you think you've got the CSS right, but the browser just isn't displaying it correctly.
-
Debugging Styling in the Browser
So now let's debug styling inside the browser. If we come back to our page in Firefox in this case, we have a plugin installed called Firebug. All the browsers have their own built-in tooling. I like to use Firefox specifically because the Firebug tool I think is a little bit more powerful than the built-in tools on the other browsers, but if you want to get used to using the Chrome tools, using the IE tools, or using the Firefox tools, it's probably a good idea to get a little familiar with all of them. We're not going to cover all of them in this course, but they all work in a pretty similar way. In most cases when you hit F12 the console for the tools will show up, in this case these are the Firebug tools. When we're debugging CSS what we really want to look at is what the CSS is for certain elements. So in our case we can go to the HTML tab and as we open up the file that we're looking at and hover over elements you'll actually see them highlighted in the browser. These highlights are showing in blue the content size and then in yellow the margin size. You'll see that it's going to be different for different elements. Let's go down to the header section as well or the main section now. The main section you can actually see all three, the blue is the content, the purple is the padding, and then the yellow is those margins we had specified. By clicking on one and let's go ahead and click on our form class, we can see to the right what properties have been specified. So this is showing all the matching styles. The simple form style, the bordered image style, the main style, and then finally the body style. All of these are applied to this element in order to get it to look the way it does. What the tools allow us to do is actually to change this stuff and see what the result is. This isn't changing the underlying file, this is just changing the live view. So if we look at our form and we go to padding we can just put in another value like 15 pixels and we can see it change on the screen or let's say back to zero. We can also, anywhere there's numbers, use the arrow keys to just sort of go up and down so we can tweak these to get the look we want. The same is for non-numeric values, so if we look at let's say vertical align as we push the up or down arrow it's going to go through all of the valid values and change them in the browser. Now in the case vertical alignment doesn't change any of those values, but if we did it for display we can see this is what it looks like inline, flex, block, et cetera. And so we can kind of experiment and learn what the different values for these properties are. Once you've changed these values to the way you want you can actually right click and copy the entire rule and this is a good way to take a rule that you're modifying in the browser and go ahead and paste it back into your original source code. Another thing that this is important in seeing and that is the cascade rules. So I want to select an element on the page. I can actually use this inspector and the different tools call it something different, but this is where I can actually go and select with the mouse an individual element I want to look for. You can see it sort of highlights it as I hover over it and I'm going to go down to the li items inside of my menu and if I click on the li we can see that this header nav li is what we created in the last section, but because we specified the font size, the font size for the body has been checked out. That means that this more specific rule has overridden this rule and so we can actually see the cascading nature of CSS here in person. As you're testing these things out you can actually click on this hidden checkbox, it doesn't show up until you actually hover, in order to disable one of the rules. Now instead of having to delete them you can just disable them for a minute so you can see the difference between them and if you're having a problem with an individual style, being able to start disabling pieces to see which one was the one that was actually involved, it can help you sort of narrow down which one's the problem. And notice that when I disable the font size in list item that this one becomes unselected because this becomes the default value now because the body no longer is overridden so it really applies the entire set of rules to your CSS in live and this is really a live view of them. And so using the tools when you're trying to debug CSS I think is a great way to not only find and solve problems, but also learn how CSS really works. Because in most of the tools you're even going to get IntelliSense, so if I decide that I wanted to have border here as I type bo it would start to show border and as I type, even go down to some of the other properties. So it gives me a lot of flexibility about sort of running through and testing my CSS. I suggest you use the tools, again, whatever browser you use for development you can use their tools, but eventually you're going to probably need to learn the tools for each of the browsers because you may find that some of the problems you're having with CSS are browser specific, so being able to go into IE and finding out why something doesn't look right in IE, but looks fine in Chrome and Firefox or vice versa, means you're going to have to learn the tools for each of the browsers. They're very similar so it's not as big of a task as you might imagine. Let's wrap up this module.
-
Summary
So in wrapping up this module, we've learned that HTML itself is structural. You can create the look and feel of your app through the styling stack. You can define the UI, the formatting of each element, the formatting of the text, the look and feel of your application strictly through the styling of your app. Leaving HTML as structural as possible means that you're going to have that separation between what you're dealing with as the structure of your HTML and how it looks. By using CSS or cascading style sheets you're going to have a way to support the shared overridable styles for your webpages and really your entire website. Each of the rules in CSS has a set of properties that are applying to a certain set of elements. In this way those set of elements can be defined as a selector in the CSS to tell the browser how to draw your HTML. Understanding the nature of these CSS selectors is key to being able to style your site. So learning the different mechanics of id selectors, of class selectors, of element selectors, of relative selectors, are all going to benefit the CSS you're going to write. It's also pretty critical that you learn and understand the box model as we have described it in CSS so that you can really understand how the sizing and layout mechanics of CSS work with HTML. We've also seen that using the cascading model of having more specific selectors apply their rules to individual items on the page is how the cascading allows for this overridability. These rules for cascading aren't always intuitive, but certainly we've seen that using the browser tools we can see how that cascading is actually happening. Ultimately you will find times when you need to drop down and debug your styling using the browser tools. And aside from being able to debug these problems, it'll also be a very effective tool for learning CSS itself. This has been the styling your HTML module. My name is Shawn Wildermuth of Wilder Minds. Thanks for joining me.
-
JavaScript
Introduction
In this next module let's talk about JavaScript. My name is Shawn Wildermuth of Wilder Minds. We'll start by discussing what is JavaScript. I'll show you how to include JavaScript, start with some of the basics of JavaScript, look at variables and types, conditionals, functions, scopes, closures, objects and arrays, and finally looping. Let's get started.
-
What Is JavaScript?
So what is JavaScript? The elevator pitch says it's an object oriented dynamic language that has become the lingua franca of websites, but isn't limited to its use on webpages. What that really means is it's a very popular language right now. It started with humble beginnings as just as a scripting language for websites, but it certainly matured into a pretty robust language that is used to power websites, but also back ends these days. It's also being used to automate a number of different types of systems. JavaScript is one of those languages that you really should have in your arsenal. What I've found when talking to new web developers, JavaScript gets sort of a bad reputation. It does have humble beginnings and some decisions it made early on certainly hurt its reputation. You can do JavaScript and do JavaScript really well and the trick is to learning its patterns. Don't try to take existing languages that you're working with and try to shoehorn your knowledge of those languages into JavaScript. Learn JavaScript for JavaScript really is. So first and foremost JavaScript is object oriented. Sometimes developers don't want to think about JavaScript as being object oriented because it doesn't have classes in the traditional sense. It uses prototypical inheritance instead of class based inheritance. It's also a dynamic language, which means it's often thought of as a type-less language, but instead it's a dynamically typed language. This means types can change and variables of certain types can change their types. You can opt into some level of type-checking as well or use a higher level language like TypeScript or CoffeeScript to get the sort of type-checking you might want. JavaScript is often admonished for the lack of compilation. If you come from a high level language like C# or Java, you may be used to a compilation step where things are checked like type checking, but also packaged so you're not delivering pure code. JavaScript is purely considered an interpreted language, but in the case of most instances and most modern browsers and certainly on the server, JavaScript is just-in-time compiled like most other high performing languages. In fact, languages like C# and Java when they are compiled they are compiled into an intermediate language that is then just-in-time compiled. JavaScript sort of skips that and JavaScript becomes that intermediate language that is then read and then just-in-time compiled as necessary. So these performance characteristics in certain cases can be just as high as other high level languages. Enough shop talk, let's see it in action on a website.
-
Hello JavaScript
So let's go ahead and write our first lines of JavaScript on a webpage. If we look at the index.html form our previous modules, let's go ahead and create a new tag called script. Script is normally used to load JavaScript, but it could be used for other languages. So we need to tell script that it's type is going to be text/javascript, that's it mime type. And then we can start to write script directly here on the page. A function that is built into the JavaScript language, though you probably should never use in production, is called alert and this is just going to allow us to pop up a dialogue on the screen. And I'll just use it to pop up the phrase hello JavaScript. Let's see what this looks like in the browser. If we refresh we can see here is the alert dialogue that was popped up with the text we typed into it. So we're actually running JavaScript when we launch this page. Let's go back to the page. And here instead of using simple alert well use a keyword in JavaScript called var. Var is allowing us to create a new variable that we want to hold some amount of data. This data could be a number, a date, a string, or more complex types that we'll look at later. In our case I'm going to have it hold a string, so I'm going to call it message and I'm just going to move this hello JavaScript into our new variable and then I can use that variable in a number of places, in this case I'll use it for the alert. If we go back to the browser, unsurprisingly we see the same code. But usually we don't want to use alert. Instead if we want to sort of run out debug messages we can use an object that exists in JavaScript called console. Console is actually the debug console that's out there and let's just write out to its log the phrase message. Back here in the browser if we use the browser tools, which we talked about at the end of last module, we can look at the console and when we refresh we can see that message that we spit out, hello JavaScript, here in the console and we'll use the console a little bit in the next few video clips to text some JavaScript ideas. Let's close that for now. And if we look at the HTML here on the page we can see that we have several parts of the page that we can interact with. Down here there is a div we created earlier called results. And results just contains some text. We can manipulate that with the HTML. We can do that by trying to get a reference to that element and let's call that the results div. And we can call document, which represents the dom or the hierarchy of elements on a page and there's a method called get element by id and here we're going to give it the id of some object on the page we want. If we go down to the bottom again you'll remember that the id for this guy was results. So if we come in here and we say results we'll have gotten a reference to that item on the page and then we can simply use several types of properties that exist to change the contents of that div. In our case we're going to say results div.innerHTML and here we're going to just supply the HTML that's going to be part of that page. I'll make a little paragraph and say this is from JavaScript. If we go back here to the browser and refresh we should see that this should say this is from JavaScript, but it doesn't. And why is that? The reason isn't all that obvious. The problem is that when we run this code here, remember we're running this code to spit it out to the console and it seems to work fine, but this code isn't running correctly and why is that? One of the things we're going here is calling the document get element by id to look at something in the document, but this is actually being loaded and executed as soon as possible and because it's at the top of the page it's being executed early. So because of this we usually take script blocks and put them at the bottom of the page so that all the elements on the page have been loaded already. We'll look at some different techniques for dealing with this, but for now putting them in on the bottom of the page is the right thing to do. So I'm going to cut them from the head and put them just inside the bottom of the body. It's usually where I put all my script tags. Now I haven't changed the code here, I've simply just moved it to the bottom of the page. And we can now see that it's displaying and running that code correctly to show it from the JavaScript. Again, that's because all of this stuff is being read by the between including the script and the script is trying to execute as soon as it has been read, but if all the elements on the page haven't been drawn yet or haven't been loaded yet, it's going to beat the browser to looking up what's in the document before it's had a chance to actually load all those elements. Putting it at the bottom of the page will help us. We'll look at some other techniques in the next module for getting around that, for guaranteeing that everything's going to be loaded before we run some code. If I go back to the code for a minute, you'll see that in this case we have some inline code directly in the HTML and much like the way that CSS shouldn't be using inline styles, you probably shouldn't be using any inline JavaScript either. So let's do that next.
-
Including JavaScript
So now let's talk about how to include JavaScript on a webpage without inlining it. As we saw in the last clip, our script code here being inline on the page is interesting, but it makes it a little harder to do things like running tests and to reuse this code and all those sorts of things and so much like the way we break out CSS we normally break out our JavaScript as well. So in this case I'm going to create a new file and folder for JavaScript and I'm just going to call this our index.js, though you could call it whatever you want. That js is the extension for all JavaScript files and depending on what editor you're using for your web development, the .js will guarantee that you get some syntax coloring and that sort of thing. I'm going to start with a comment and it uses c style comment, so double slash or slash asterisk and ending with an asterisk slash, they both work. And at the top I'm just going to give it the name. So we can see pretty clearly when we open a file that we have the correct file opened and I'm going to go grab the contents of this JavaScript as is and move them into the index.js. So what we're going to do here instead of having the script inline is we're going to use a new attribute called source. This is where we can point it at the file we want to load. And this is how you load external JavaScript. In our case we're loading some JavaScript that's relative to the page and so we can go ahead and include the directory name here and then the file name. But this also could be a fully qualified web URL, so I could be going out to http://cdn.google.com and then the name of some common library out there, like jQuery or AngularJS. So you can use this to pull in both first party code you're writing and third party code that you're using on your website. That's all that's need to bring it in. One thing you may be tempted to do is going ahead and ending it prematurely like that. But because it is HTML there are certain tags that need to have a beginning and ending tag and script of one of those. This is a mistake you'll invariably make a couple of times until you really get ingrained with making sure the script has an ending tag and not a self closing tag. If we look at the same code and just go over to the browser and refresh again, we'll see the same code is executed. There is our this is from JavaScript, but in this case it's actually being loaded from an external JavaScript file. We can see this in the browser tools by going to the script tag. We can see that there's now one scrip that's actually being loaded for our page and actually look at it. Let's start looking at the language itself so we can see some of the basics of the language.
-
Variables and Types
So let's now take a quick look at variables and types. If we look at the code we've written here, we can see that we have a couple of different variables that we've already declared. We can actually look at the type of both of these by using a function in the language called type of. So let's go ahead and write to the console, message is and just let's use the add to concatenate a couple of strings together and look at the type of our message type. Let's do the same thing with our results div. So we can just start to understand the type system in JavaScript. And I'm doing this using console.log so we'll have to look at the console in the browser. So if we refresh the page we can now say that message is a string, so the message variable is of type string and the results div is actually a div inside the document, but the types information is only going to tell us it's an object, therefore it's not a primitive type. Let's look at a couple more of these. Let's create some new variables and let me create a variable that hasn't been created yet. I'll just call it none, where I'm not actually assigning anything to it. And I'll do the same thing I did with the other types here and I'll create a new variable for a number and let's just say zero and let's look at a Boolean type, like true/false. Now there's a handful of these primitive types as well as complex types out there so I'm not going to cover the breadth of every type here, but I just want to give you a taste of the different types. So we can see that that message is still of type string, results div is still of type object, and that a number here is of type number and true/false is Boolean. All that's pretty much what you would expect. The type that is confusing here is none. Because it says none is of type undefined. This is actually something we can test for. Undefined is a special keyword in JavaScript so you can test to see whether a variable has ever been assigned a value, therefore has a type. So undefined ends up being one of the types out there. Now as something you'll end up needing here and again you can imagine it tested for things like whether pass in variables have been initialized or not. One thing to be aware of about JavaScript by default is it doesn't actually need variables to be defined before they're used. That may seem a little odd, but let me give you an example. So I could come down here and assign a new value to a variable with a name that we've never used before. Let's say nonexistent was an variable name we wanted and I could just say this shouldn't work. Now the problem here, let's go back to the browser and refresh, is if we look at the nonexistent type, the console lets us type on the bottom of the screen to write adhoc JavaScript, you'll see that nonexistent the value of it is this shouldn't work. Most languages force you to declare variables, in our case with the var, before using them, but because of what many think is an oversight with the original design of the JavaScript language, variables don't need to be defined first. The problem this causes is what if I didn't really want to use a brand new variable, but I simply misspelled it? So what if I said messages equals shouldn't work? Now here's a variable I think I'm redefining, but I misspelled it, I added an s to message instead of messages and JavaScript will just go about its way and go, well that's fine, we'll create a new variable called messages and I'll spend hours debugging this code trying to figure out why assigning this never gets changed up here and why we have this sort of hanging new variable that was just created by accident. The way to solve this is that newer versions of JavaScript ECMA 3 and beyond, which is these days a pretty old version of JavaScript, most browsers support at least ECMAScript 3 version of JavaScript, you can put a little string at the top called use strict. And what this tells the compiler is to use some stricter rules when you're parsing this JavaScript. And one of those stricture rules is don't allow undefined variables. Now this use strict is something I'd like to encourage people to use, but it is just a string. Why is it just a string? It's just a string because in older browsers or on devices that don't support later versions of JavaScript this is just a string and it is perfectly valid JavaScript and it will be completely ignored. It has no side effects. But in newer versions of the JavaScript compilers they'll see this and go, oh we need to be a little bit more strict in how we interpret this JavaScript. Let's see what happens when we leave this code in our example. We actually get a reference error, an error is thrown by JavaScript that says assignment to an undeclared variable messages and that's because strict is on so we can now go, oh this is no longer valid JavaScript. So we need to go ahead and comment that out or delete it, whatever you see fit to do in this case, but it's a piece of error code so that we can actually see what's going on and see what's wrong. So adding use script to most of your projects is not a bad idea. Let's move on to conditionals.
-
Conditionals
So now let's talk about conditionals and how comparison works. In the last clip I talked about how this none variable was of type undefined. This is a pretty common comparison you're going to do. So we can use the if construct in JavaScript to test for something and if whatever is in the parenthesis is true it will execute what is inside of the curly braces. This is C style or it's common to C# as well and then of course you could have else or else if with another conditional in it. So these are pretty standard comparison blocks. But it's what happens inside, let me get rid of the else if for now, it's what happens on the inside of here that makes JavaScript a little special. So if we go ahead and say if none is equal to undefined, console.log, none is undefined, we can actually test and you'll see that undefined is put in a special color here because it is a JavaScript reserved keyword, it has a special meaning and that is that this has never been defined as we can see here. The variable exists so we can use it, but it's never been assigned a value, it's been undefined as a value. Here we can see that that conditional in fact did what we expected, but JavaScript conditionals have a special behavior here and that is all the types are compared together. Let me give you an example and then we'll come back to this example in a minute. Let's say that a number variable was the number 10, so it's still a number and you would expect that if I said if a number equals 10 then we could just write out to the console, right? And you would expect this to run, 10 is 10. Well what happens if we decide to say what if 10, remember this is a number not a string, is equal to this string of 10. Should it be equal? In JavaScript it is. And the reason is that when you do comparisons all of the types are coerced to ones that can be compared. So in this case it's taking this number and saying, oh you're trying to compare it to a string, therefore I'm going to convert this to a string and then do the test. The double equal sign in a comparison where the exclamation equal sign for a negative comparison, they both use this coercion. So you can assume that it's going to try to find types that are actually comparable in this case because they're doing a comparison, they're not doing an equality test. So how do you change that? You do that with a third equal or in the case of a negative test a not equal equal. So now if we do this what's called an exact comparison, we can see the 10 equals 10 does not show up because these are not exactly equal or identically equal. This coercion has some benefits though. So if I wanted to say if not none, which is going to end up being the equivalent of saying if none is equal to undefined I can actually just use this Boolean expression because it's going to take this undefined value and convert it into a Boolean since it looks like that's what I want to do. And this is same as saying, none does not equal true, right? Putting the exclamation point before it is going to allow us to simply say if that is not a true value then show that none is undefined. We can see that is still happening in our JavaScript. So this type coercion becomes important as you do tests. So knowing when you want to actually test whether the values are compatible or whether the values are identically equal, you're going to need be aware of using the double equals or the triple equals and of course the single equals is just for assignment. And so if you had tried to do this it would work because it would simply assign this to the variable of a number and because this assignment worked it would return true. So try to avoid single equals inside your if in all cases. Now that we've looked at some basics around types and comparison, let's look at functions.
-
Functions
Next, let's look at functions. So function starts with the keyword function. And we'll go ahead and give it a name and in this case it will be show message. A function has a set of parenthesis in which you can have function parameters and then a set of curly braces just like in C# and C++ and C that designates the body of the function. In our case we'll just accept one parameter, which will be our message, and then just use the console.log to go ahead and dump it into the console. So it's not a very interesting function at this point. Once we've defined it we can just call show message and then supply some information. The set of parameters, in this case we're sending it a string. So if we look at the function it's a very simple concept, it's some repeatable code, something we're going to call over and over again. If you've dealt with other languages this should be a fairly simple construct. One of the problems that you're going to have in functions though is the problem of overloading and the reason overloading is a problem is that when you think about most languages out there they have the same concept of having a function that may have one or more parameters, in fact having different versions of it. So let me give you an example of this. So I many have another function with the same name, but let's say I want to take two parameters instead and I'll do what I did before and I'll put a little plus there so we can tell the difference between them and just concatenate all three pieces together. And I'll call it this time with two pieces of information. So if you were dealing with a language that wasn't JavaScript, you might think that the first of these was going to call this version of the function with one parameter and that the second would call the other. But if we go over to the browser we'll see that both versions of show message use the second copy of the function. The reason for this is that there can only be one function with each name. If we want to support something like additional parameters, there are a few different ways to handle it, but overloading the function, having two versions of the function that accept different parameters, is not one of them. Because in this case by defining show message again, all we did was override the show message. A common way to handle this is actually to use the test for undefined. So if more was defined or provided if you want to think about it in those terms, then we'll go ahead and show the message and include the more, but if one of the cases didn't include a more, like our first version, we'll just show the message itself. So it's up to you to handle the multiple parameters and when parameters go missing. We refresh it and we can see we're now getting that second version of show message, but now it's doing the right thing, showing the first message and then the additional second message if one was supplied. So while we can define named functions like we have here, we don't always have to create functions in this way. Functions are first class citizens of JavaScript, are in fact a different and special data type called a function type. So that we can do things like this, so in this case we're defining a function as just a variable and of course to execute it we can just call show it. So the different syntaxes here aren't all that important. There's a little difference here in that the show message is going to be available to any code after it's been defined here. The same with the variable here, but with the variable we could more easily or more obviously pass it as a parameter for instance. Let me give you an example of that. Let's create a new function called show it then. And in this case we'll accept two different parameters. A message to show and then something to do after it and I'll call that something a callback. In this case I'm just going to use that show it and say show the message and then callback parenthesis. So this callback is a function that's being passed into us. This function that's being passed into us then can be executed with or without parameters. In this case I'm not going to include parameters, but I could certainly send in message or even some hard coded set of parameters as well. When calling it, a very common pattern in JavaScript is to include a function as an inline parameter. So here we'll just say function, again, notice it's an anonymous function, we don't have a name for it, but we could have simply put one of the function names here, but in this case we want to define that something's going to be done once our messages has been shown. And we'll just say callback called, just to be easy. So this is not defining an function here. This is calling a function, this function above it. But we're supplying our callback as a parameter to that function. So this is an important concept because it comes up a lot because JavaScript has a lot in it that ends up being asynchronous. Things like registering for events, making network requests, et cetera, those all expect you to be able to start execution of something and then wait for something to happen, like the user click a button or the network requests complete. If we look at this in the browser we'll see that they show it was called and then once they show it was called with some data, that callback was then executed. So when we called this, it took this message, this first parameter and called show it in order to spit it out into the console and then executed this callback and this callback was simply this function that we had defined to say here's the thing I want it to do. And this is very much related to the way that things like lambdas work. Lambdas in C# and later versions of Java, in Ruby, etc. A lot of other languages have this construct, you just need to think of this as just a data type that has callable functional code in it. In the next module when we start to look at event handling, networking is done with jQuery, we'll see this pattern quite a lot.
-
Scopes
Now that we have a basic understanding of functions, let's take a look at scopes. So in the big picture the idea of a scope is simply where global things are attached to. In the case of all the code we've written here, the show it variable, the functions called show it then, and the show message, those are all attached to what's called the global scope because we're not inside of anything else, all the variables we're creating here are inside of a scope that everyone shares, every JavaScript library on the page actually shares this. So you need to be a little careful about using the global scope. So for instance I create a new variable called in global. This variable is created and then attached to the global scope so I can certainly do things like use it here in the global scope, right? Everything that's part of this global scope is actually attached in a webpage to an object called window. So I look at window.inGlobal. This is actually attached to that window object, the window is the parent of the webpage you're actually sitting on, so window ends up being the collector of everything global. So every function we created will also be here, show message, show it then, they're all part of that global scope. Inside of JavaScript there's really only one thing that will create smaller scopes and that is a function. In different languages they have the different idea about what constitutes a scope, a class, a name space, et cetera. But in JavaScript the only thing that creates a scope is a function. So if we create a new function called test me for lack of a better name, we can actually use things that are in our outer scope. What should come as no surprise is that we create a variable inside of test me and then we try to use it, let me move this up a little, this will be usable as well because it's inside the scope where this code is being called. Hopefully that's not surprising at all that that works. The idea of a scope being important or the function level scope being important is back here outside the function because if we try to then write, this should fail because some message is not included, we're back out in the global scope because it was created inside the function, therefore it has no visibility outside the function. Some message not defined. Of course, some message is defined, it's just defined outside the scope of that variable. So this is not supposed to ever work. This idea of scopes and how they work is important especially when we start to look at the way that things called closures work. Let's do that next.
-
Closures
Closures are an important idea in JavaScript. So I want to make sure that you understand them clearly. The idea behind a closure and we saw that with the global scope in the last clip is that it allows outer variables to be visible in inner scopes and this happens regardless of the lifetime and that's kind of the key piece here. Let me show you a little piece of JavaScript to describe this. So let's say we have a variable called x, we have some function and this function uses that outer variable x and then some time way later this some function is called, even if this has gone out of scope for one reason or another, it will be maintained in memory because the function here needs it. So as long as the function lives, this variable has to live for the same amount of time. The JavaScript runtime does this by wrapping it or creating a closure around this variable because it knows because of this function that it is necessary. Let's see how this works in practice. Let's go back and use that show it then message that we did a little earlier and I'll just type with closure so we know what it was about and then we're going to use a callback to go ahead and show yet another message. But this time I'm going to use the some message that's outside of the scope of this new function, even this little callback function has its own scope. So if I call show it with our some message, we should see that it keeps this temporary variable around until this callback is executed and this is an interesting point because normally this some message is only going to be alive for the scope of the one execution of this function. But in our case, the runtime is going to keep the some message around because it knows it's necessary for this additional callback. So we can see the call to with closure and then when our callback was issued this some message still lived. It had a longer life because that closure kept it available. So in most cases you're not going to need to think logically about closures, but gone are the days where you have to store some global data in order to keep it around for some function or callback that needs it later. The JavaScript runtime will handle that for us. Let's look at objects and arrays next.
-
Objects and Arrays
So the next topic to look at are objects and arrays. I'm going to clean up some of this boiler plate code we have here and comment out everything below this because we're going to start to build something interesting. Let me make some space. I'm going to create a new variable called result and for the value of result I'm going to use curly braces. Curly braces are an indicated that what I'm going to create is a new object. The nature of the object oriented system in JavaScript is this idea of objects. Now objects don't have a type necessarily to them. In our case we're talking about objects that don't have a define type necessarily to them. There is a way to create things that look and feel like classes from other languages in JavaScript, but we're not going to cover them in the course. In our case we're just talking about objects and an object is just a set of name value pairs. So I can say name: jQuery, language: JavaScript, score: 4.5. And this ends up being an object. This object can now be accessed by using the dot syntax. So if I want to say console.log result.name, that will actually work. Because what it's done is this object notation has defined a set of properties for that object. Now they don't all have to be properties. We could also have a function as a property or even other objects. Now when we have other objects as properties they are going to have then your own set of curly braces and allow you to define its own properties. In this way it really is just a hierarchy. So we think about JavaScript being object oriented and it really is because we can simply have these objects. Now objects also support mutation, so I can very easily just say result.phoneNumber = 123-456-7890 and now when I use this I can actually call phone number and it'll display that correctly because objects in JavaScript allow you to add new properties at any point. This is one of the places where typical high level language people, C#, JavaScript, C++, et cetera, get a little nervous because the type system is very loose in JavaScript. It's loosely typed in that way and that's actually kind of a good think, you just have to understand the patterns around JavaScript to get comfortable with that. The other kind of object that we're going to talk about here are arrays. Now we kind of think of collections in many languages in certain ways and think about different kinds of collections and a lot of that is supported, but the simple array, the simple collection, the simple list is something that's built directly into the language as well. And if I create a variable called result and put in two square brackets that's going to tell it, hey you're defining an empty array, an array with no members. Now we call it an array, but array has sort of a fixed meaning, it's more like a collection where we can push items in, pull them out, sort them, et cetera. It's a fairly mutatable array. The way we can add items is by calling push. In our case we'll go ahead and add that result as the first item in the collection of results. We could, of course, say push and give it an object notation as well. More normally if you have the data in code that you want, you're going to actually use the object notation along with their array notation to create your collection. And I'll do that by just moving this down. I'm going to copy this into my results and let's put a comma after it and create yet another one and we'll go ahead and use some editor inheritance here to more quickly build up a new one, call it UI, change the score, and I'll leave the rest the same. So we now have a collection that has two members in it and each of those members is an object that represents a bunch of properties that we actually care about. And let me comment out a couple of little pieces here that we're not going to use anymore, like this result. Now that we have an array, there are a few things we can do with it and I'm not going to cover most of them, but let's talk about the easiest, which is results.length. Here's a way you can test to see how large the array is and then of course we could say console.log, results, and then just the use bracket syntax to indicate which item in the collection we want. In this case we're looking at the first item because arrays in JavaScript are zero based. Once we get at this we could just say something like name to point it out to the console as well. So the way you're used to dealing with collections in other languages should be pretty comfortable here. Let's take this one step further and talk about looping on our next video.
-
Looping
Let's see how JavaScript handles looping. JavaScript, because it came from the world of C and C++ still uses the standard C style loop and that's where we can create a variable at the beginning and if we're just numbering through an array we would start it with zero. We would then take the x and make sure it's not too long, in our case that would be results.length and then the last piece of the four is incrementing the x so that on each loop we're incrementing the x and then testing this second piece over and over again. So when this starts x equals zero, x is still less than the length and then it runs what is in between the curly braces. Once it's done with that it increments the x and then reevaluates this. If this continues to be true, it executes it again and so on. As soon as it executes it as false it falls out of the for loop. So in this case we can get a result, which is going to be our results based on which item of the loop we're going through and then we can do something with it. For example, just write out to the console the name of each item. If we look at this in the browser we can now see we're seeing each of those items that were in the collection, we're walking through them one at a time. Looping also allows you to break out of it. So if we want to say if result.score is less than 4 break. So if it finds an item in the collection that is less than 4, which is our second item, it's going to break out of the 4 loop entirely. It stops the execution of the 4 loop and falls down to the next statement after the 4 loop. We can see that here because the first jQuery is executed, but the second jQuery UI is skipped because we've broken out of it. If we change this to greater than 4 we can say continue and continue is another way to abort the 4, but while it doesn't break us out of the 4 it forces it to return back to the top of the 4 and increment the number again. So in the case of continue everything after it is ignored and it continues back at the beginning of the 4 statement, increments the x and tries again. So in this case because our score is 4.5 on the jQuery and less than that on the jQuery UI we should only see the jQuery UI in the browser, which is exactly what we see. So loops are really simple for walking through any sort of collection. Being able to walk through collections and do something interesting with them is something that you're going to find is useful is your web development. Now we've talked a lot about the basics of JavaScript and our next module we'll delve into how jQuery can make writing your code that you might be using in JavaScript a lot easier and more web centric. But let's wrap up this module first.
-
Summary
Let's just wrap up what we've learned about JavaScript. Hopefully the point I've tried to hone in on is that JavaScript is a real language. You should treat it as such. Your fear of coming to web development may have been tainted by people talking down or talking bad about JavaScript. JavaScript has certainly weaknesses that maybe other languages don't, but most languages have pros and cons. I think you'll find once you've worked with JavaScript a little bit and worked with it in the correct way that you'll find it pretty easy to work with. Using script tags on web pages is a very easy way to get your JavaScript onto the page and loaded in the correct way. Like most languages you may already know, JavaScript includes the standard simple bits like variables, loops, conditionals, et cetera. Objects and arrays are a little different in JavaScript than other languages, but they are first class citizens of the language and you should treat them as such. You should get comfortable with looser typed or malleable or mutable objects and arrays over time. And in many ways JavaScript was written around the idea that functions are a key to the language because you're going to be using functions as sort of the bread and butter of componentizing your JavaScript, understanding the way that scopes and closures work together is key to doing that correctly. This has been the module on JavaScript. My name is Shawn Wildermuth of Wilder Minds. Thanks.
-
jQuery
Introduction
Welcome to the using jQuery module of our quick start. In this module we'll discuss jQuery. I'll start out by explaining what jQuery is. We'll grab jQuery from the jQuery.com website, show you the basics of jQuery, talk about event handling in jQuery, using jQuery to query the document, to change the document, to perform networking tasks with jQuery, and finally we'll work with some forms with jQuery. Let's get started.
-
What Is jQuery?
The simple answer to what is jQuery is that it is a JavaScript library for use of client side web development. Its purpose is to enable developers to create interactive websites that work across different browsers. This includes handling interaction from the user, manipulating the page, as well as performing network requests. JavaScript and the web have been around for a long time, but before jQuery came around it was much more difficult as the different browsers supported different things, different versions of JavaScript, different versions of the HTML spec, it become more difficult to write one set of code that would perform well across these different platforms. The goal of jQuery was to hide some of these differences so that developers could focus on adding functionality, not on cross browser issues. But in order to show you what jQuery is, let me show you it in action.
-
jQuery Basics
So let's take a look at the basics of jQuery. So if you start at jQuery.com you'll end up on this page. This is the home of jQuery, includes things like the API documentation and the ability to download jQuery itself. Now you can get jQuery in a variety of ways, but we're just going to download the library and use it directly from our own site. jQuery comes in two flavors, jQuery 1 and jQuery 2 and the big difference between these two versions is whether it supports internet explorer 6, 7, and 8. Now this is an important difference. The reason they're maintaining two versions is that jQuery 1 is larger and in some cases slower than jQuery 2, but if you need to support these older versions of internet explorer you're really going to want to use the older version of jQuery. They're maintaining a lot of features in both sets of jQuery so you're not losing a lot of functionality between them. I typically start with jQuery 2 unless I find out that our users are actually using these older versions of internet explorer 6, 7, or 8. So I'm just going to download the compressed version and drop it in our project. And here I'll put it in the same directory as our other JavaScript. Back here in the index HTML I'm going to add it to our project. Because it's a base library I want jQuery script to happen before our own scripts. So I'll use the same script tag, but in this case I'm going to include jQuery as the name of the library. First to do the work we want to do inside this page with jQuery, let's go ahead and place the contents of our results pane with a new div that we will call results list. Results list is going to be the actual listing of the different results on a page. If we go over to the index js, much like earlier we had gotten the results object and then used innerHTML to set it, we're going to do the same thing now that we have jQuery in the picture. We're going to go ahead and get the result list from the DOM and we can do that by using the jQuery function and jQuery takes as this first parameter a CSS selector syntax. So jQuery is leaning on the CSS selector syntax you're already learning for CSS to figure out how to find the elements inside your HTML document and so we can go pound, like the id, and then result list, this is the name or the id of the element on the page, which we see here as a result list. This will return the result of this query. jQuery is querying the DOM for some elements. Once we have this, we can use several methods for setting different things about this element. In our case we could use HTML to set some arbitrary HTML, much like we did up here with innerHTML or we can even use the more simplified text, which is just going to change the textural content. If we save that and refresh the browser we can see it's now setting it from jQuery itself. An interesting point about this is the jQuery object itself that we're using to do these queries has an alias and that alias is the dollar sign. In most jQuery code and examples you're going to see out there you're going to see them use the dollar sign syntax because it's shorter. In JavaScript you're allowed to use certain symbols as variable and function names and so they've decided that the dollar sign here is going to be an alias for the entire jQuery API. So that we can just use dollar sign here as an alias for the jQuery object and the rest of this will continue to work just the same. As we can see here in the browser, it continues to run. Next, let's leverage jQuery to do some event handling for us.
-
Working With Events
Next, let's go ahead and handle some events so we can interact with the users. If we come back to our HTML page, let's go ahead and add a quick button before our results list. And here it'll just be a quick button that will allows us to hide and show the result list when we click the button. So this would be a really simple interaction with the user. The name of this button is going to be toggle button via an id tag, so we should be able to just get our toggle button by calling, you guessed it, pound toggle button. Once we have it, there's a special function on the returned object called on. On allows you to handle events of different kinds. Now as you mature as a web developer you learn a lot of these different event names. There's no real magic to finding all the event names, they're in documentation, out on the web, or on w3c.org. You're going to need to learn these different events. But buttons have a very simple event. If you've ever done any Windows development it should be obvious, and that is an event called click. We're going to tell it that we want a handle when this button has been clicked and we're going to do that by supplying the first argument as the name of the event and then the second argument as a callback function. So when click handles on the toggle button let's do something. In our case, let's go ahead and show and hide the results list. Now we already have the result list up here, so like we talked about in the last module we should be able to use it as a closure into the toggle button here. So we'll say resultlist.toggle. Toggle is a function inside of jQuery that says if it's shown hide it, if it's hidden show it, and we'll actually give it a little length in here. One of the parameters of toggle is how long it should take to animate the hide and the show and so we should be able to see, if we're paying attention, that the list appears and disappears from view. Let's see if this is working in the browser. We have our button here and when we click it we should see that in a half a second it hides that result list and if we click it again it should show it. Hide, show. We have our first little bit of event handling directly using jQuery. And the syntax for doing it is pretty simple, what event do I want to handle and then what is the code that should be executed when it's ready to be handled? Now that we have this toggling, let's go ahead and toggle the name on the button as well. We can do this by testing what is the text of the toggle button. So in this case we're saying if the text is hide we want to do something about it. And instead of this being a traditional sort of property which you might be used to in other languages, jQuery has a function on each of the DOM objects called text, much like we used it up here to set the text. If we don't supply any arguments it knows to return the text and then that way we can compare them. So I'll use text again to change it to show. So if it's already hide let's make it show else I'll set it back to hide. If we go over to the browser now, we should see it switch back and forth exactly in the way we want. But there's one more problem here that's not all that apparent. If we go back to the HTML you'll remember we put the script tags on the bottom of our page to try to ensure that the whole DOM or HTML was loaded before our JavaScript was. Now because we're running this all on our local machine it's pretty much guaranteed to happen in that order. It's not 100% guaranteed, but it's pretty much guaranteed. The problem we have here is that that little case when they don't load in exactly the same order could cause us some problems. In that edge case where the DOM isn't ready before our scripts load, depending on the browser, can cause you some problems. And so the way to handle this is actually to handle a special kind of event in jQuery. jQuery allows us to wrap any element that we've created or that is in our DOM and we have as a raw DOM object into a jQuery object that wraps it and we can do this by starting with that same syntax, but we're simply going to give it that object and so in our case we want to wrap the document object in jQuery because we want to do something that jQuery knows about to our entire document. What we want to do is call something called the ready function. The ready function is there to say give me your code that you want to execute once the document is ready. So the syntax is fairly descriptive in what it does. When the document is ready we're going to call a function, no parameters, and we're actually going to wrap our entire code, even the comments for us. So we've wrapped all of our code inside this document ready function so that none of this gets executed until we know the document and all the elements have been loaded correctly. Once that has happened we can then do all this work against the DOM like we talked about. We can guarantee that it's going to happen, it's actually an event that is fired from the browser to say the DOM is now ready to manipulate. The secondary benefit here is it takes all of this code outside of the global scope so that we're not polluting other JavaScript files we may write later that have the same names in them, it sort of protects them all in this little bubble so that different JavaScript files can't interfere with each other, but the main reason is to make sure that we are ready for this event to be fired once all of the DOM is ready for us to manipulate. So far we've talked about using jQuery to query the DOM for elements that have a specific id specified. Let's talk about querying the DOM in general so we can see the real power of jQuery.
-
Querying the Document
So now let's dig a little deeper into the way that querying using jQuery really works. If we go back and we look at our index.html you may remember we created this nav section and this nav section had a number of list items in it that contain the different elements of our menu. Over here in our code we can use jQuery again to look for those nav elements. Let's remind ourselves again that we used in CSS this header nav li to look for each of those elements inside of the menu. We did that to display them inline and change their font size. If we copy this CSS selector, this entire CSS selector, we can use it inside of jQuery. So jQuery can query anything that is described as a CSS selector. In fact jQuery adds some additional things that aren't allowed in CSS to simplify some of the code that you might write and we'll look at that in a minute. What this returns, what this jQuery function returns, is actually something called a wrapped set. Now we returned wrapped sets from all of these queries that we did earlier, but because they were against a single id it always returned a collection or a wrapped set of results that only had one member. In this case we know we're going to probably get three items here. An instinct as a developer might be to get the collection and then use for to walk through them. This is one of the amazing things about the way that jQuery works. All these same functions that we're used to, like text and HTML that I've show you already, when you execute them against the result of a jQuery, it'll execute them against all the results in the wrapped set. This only results in an effecting one because the wrapped set, because of this being an id query, always returns a single result. If we did the same thing here and say setting the text to the li items, we'll see that it changed them to all be the same item. So that executing a function on the wrapped set is going to do the same thing to each element of that wrapped set. Let's show you one that's a little bit more obvious. There's a function on the wrapped set called CSS that'll allow me to go ahead and set CSS arbitrarily. In this case I'll do font weight and I'll make them all bold. Now I know what you're saying to yourself, shouldn't I be doing this in CSS? Yes, you really should. But this will show you the power of what jQuery can accomplish imagining that you might need to set something as bold as the user interacts with the page. CSS is going to apply those rules when the page is loaded, but isn't going to necessarily know what to do with them when a user hovers or clicks or taps on something. So we can now see that all three of these are bold. The work involved to actually execute this query is nontrivial. It's pretty quick in the larger scheme, but if you have a very large HTML document this can be a little slow. So it's often a better idea if you're going to be doing multiple things, to go ahead and hold it. So let's call this list items and that will yield the same thing, but that means that if we decide to do something else, like set the font size, then this execution is going to be against that result set. It will first set the font weight for each of the items in the wrapped set of the list items and then do the same thing for the font size. But it's often the case where you might want to actually look into the result set for some more information to query against a query. Well certainly we could have changed this and created another query, like header nav li and use a jQuery specific extension to the CSS selector syntax and I'll give you an example of one first. And in this case it'll go ahead and find the first list item and set it to 18 points, but remember that by executing this entire list it can somewhat inefficient because if you have a large HTML document these queries aren't a trivial effort. We want to be able to save them as much as possible. And one way to do this is to reuse that wrapped set like we talked about. But instead of calling the CSS we can use a call called filter to allow us to then do another query against that wrapped set and in our case this will be a much more efficient way to go ahead and set the size of just the first item in our list items. So we looked at some other techniques for querying the DOM, so let's look at how to actually manipulate that DOM.
-
Modifying the Document
Now let's manipulate the document using jQuery. Remember back to the last module we had created a collection of results here that we wanted to represent some results from a query to Github. We're going to reuse these. We had originally gone through and just logged out some information. I'm going to comment that code out because we're going to do something different. We're going to actually manipulate the DOM by adding the results to the UI. Well before we use a simple for each, jQuery actually comes with a faster version of a loop for us to be able to do this sort of work. So we want to go through the results to execute something for each result to be able to display some HTML in our result list for each of those results. And this improvement to the for loop is exposed on the dollar sign or the jQuery object as a named member called each. Each is just a function and each first takes the collection we want to iterate through, results, and then a callback. This callback expects a variable for the item number and in that case I'll call that i, and then the actual item in the collection that's being passed in, in this case that's item. It can take some other parameters optionally, but these are the two that are the most common. So at this point we have as item in this callback, each of these items one after the other. So whatever happened in this code is going to be iterated over and over again. Before we start to fill in the results list let's grab that result list collection and just call empty on it. It's another jQuery function that will allow you to just take all the children or contents of an element and get rid of them because we're then going to add them back here in the for each. So the first thing we want to do in this clause is go ahead and build up some HTML and we'll just use string concatenation to do it. And we're going to do this by creating a new result where we have a div called result and inside of that there's going to be a title and we're just going to concatenate this by taking that item that represents each of the items in our list and showing the name and then another one showing the language and then another one showing the login name for the owner. So really simple piece of nested divs that represent what our new UI should look like. Once we have that we can just say resultlist.append and tell it to add this new piece of markup as a child inside the result list. If we go back over to the browser, we'll now see that we have jQuery, JavaScript, Shawn Wildermuth, jQuery UI, we've built up some markup that represents each of the results that we have mocked up in our code. Just to remind you that was jQuery, JavaScript as a language, Shawn Wildermuth as the owner, et cetera. To make them a little clearer let's go ahead and add some CSS to format those new results divisions that we created. And here we'll just create a margin and a border much like we did in the second module and just set the title section to be bolded. With this new CSS we can now see each of our elements a little clearer as individual results. Remember back when we wrote the code for hide and show, this continues to work even though the contents are getting bigger because we're hiding the entire element. So let's add a little bit more interaction by using another jQuery function called hover. Hover will allow us to do some code when we enter and leave the element with a mouse. Obviously in touch screens this would be totally different, but let's focus on desktop browsers for the moment. Ordinarily you could think you could do this by saying newresult.hover, which is a jQuery function. And the hover takes two functions, one function for entering and then another function or callback for leaving. And so when we enter it, we want to make it darker and then reverse it when we're done. Make sense? The problem of course is that hover itself is a jQuery extension. A new result is not a jQuery object. Much like we were able to take the document object that represents a DOM element and wrap it in a jQuery object, like this, the same thing works if we wrap text that represents a parsable set of JavaScript. So let's change this new result to be a jQuery object. That way we can actually use the hover here. Of course the thing we're hovering against is this new result. But jQuery, because this is a callback, will actually allows us to in fact set the this keyword as the DOM element that we hovered over. In this case the this would be that DOM element. But again we want to use jQuery to wrap it so that we can go ahead and set some CSS. So I'll do the same thing yet again, wrapping the this and just saying, and I'll do the same thing in the other handler, but set it back to transparent. So you remember this hover function is just going to set up these two callbacks. So if we've done it right as we hover and leave they'll go ahead and become transparent and light gray as you would expect. It's these little niceties that makes jQuery really easy to work with because writing this sort of code becomes trivial once you're using jQuery. So now that we have code that's showing our individual results and we can hide the result set, let's go and look at the way that calling out to Github to get the actual results so we can show them here on the page actually works.
-
Networking With jQuery
So now let's make some network requests with jQuery. Another place where jQuery can really help. If we open up a browser or other tools for looking at network requests, we can simply paste in an URL, in this case to the Github API, that describes some sort of query we want to execute. In our case it'll be a query for the word jQuery and look for all sorts of projects that have as their language JavaScript and are sorted by stars, it's just a set of query elements that are added to an API directly in a URI. Github exposes this as a public API and so when we execute it, what we're returning is a list of items. Now this syntax where it looks like the beginning of the object syntax in JavaScript is no mistake. This formate is called JSON or JavaScript Object Notation. In this case all of the property names have to be quoted, which is why you see them all quoted here, but essentially it's close to the object and array syntax we talked about in the last module. For our needs what we want to focus on is that this is going to return an object that contains the results of some query. And it does this by making a network request to Github. Let's create a variable called gitHubSearch. And we'll just contain the entire URI. Now we can use jQuery to get the results here by calling $.get. This is a method inside of jQuery that says go and issue a get against some network resource. Now in http there's a series of verbs that you can issue, post, get, put, delete, patch, options, there's a number of them, but when most browsers go and get data the verb is, unsurprisingly, get. And so what we can do here is just use this gitHubSearch URI as the source of that get and by default we can give it a callback that expects a parameter that contains the results of that get. Now this pattern of using a callback should be familiar to you with event handling, but is especially important here because these network requests are going to be asynchronous. You're going to call them here and then sometime later when the networking is done, it'll call your function with the results. So if we come over here and say console.log, r.items.length. Now where am I getting r.items.length? Remember that this r is going to represent the result of this object that is returned and one of the properties of this object are the actual items. This array of items that is returned. So r.items becomes just the object syntax for that result and then length is going to tell us how many items are in this collection. If we look in the browser and let's use those tools again to look at the console, let's refresh the page. We're going to see there are 30 results. In fact in the console it'll show you this get that it just executed and if you wanted to see what was inside of it you're going to see that the response is that same response we looked at a minute ago. So we're essentially telling jQuery to ask the browser to issue one of these commands for us. And when it does we get back in code the results of that command, but instead of just showing the length let's do something more interesting like calling a new function called display results. And let's pass it the items that are being returned. Now we haven't written this display results yet, but we've done most of the work required. This code where we went through and emptied the result list and then showed each of the results is in fact what we want our new function display results to call those results as this function. And of course this results was using these mocked up results not our real results. So let's comment those out because those are just useful for testing and teaching you how that stuff worked. But for us we're actually going to execute this gitHubSearch and then use that same code we did a minute ago, but to show you those same results. Now why would that continue to work? It continued to work because each of these items actually have the same properties, it has a bunch more, but the same properties that we had mocked together. See we have a name, we have an owner that has a login, and we have a language. So we're using some of those same pieces of data that we were before. Obviously this is returning more data, we could display even more data, but this should continue to work and let's see if it does. Once we wait a minute we can see that it returns all of these results. They're all in JavaScript because that's what the query was looking for and they're all related to jQuery in one way or another. Let's go back and look at the networking code just one last time. If we take this networking code we have this function in here that is going to be called with the results. But we don't have a good way to test for whether the results errored out or there was some problem, the network went down, Github was down, whatever the case may be, we need to be able to handle those error conditions and we could simply give ourselves another function here that happened to be our error callback. That would work and is fact what jQuery supports, but they also support another syntax, which I want to introduce to you because it makes more sense to me. It's a little bit easier to read and makes more sense and that is something called a promise. I could describe promises in depth and show you how to write your own and those sorts of things, but lets just focus on what it's going to give us in this case. If we simply call get with just the URI, the object that is returned has a number of functions on it and one of them is success and just like our code did before, success is going to take a callback function for when it succeeds. But the power of the way the promises work is I can then chain this with another call to fail so that I can do something to show or to handle the error condition. I can even add a third one here, which is done, which will be called in either case to do something at the end. So I'm not going to actually do anything in done for time sake, but we can see here that this chain of different even handlers means that it's a lot clearer to know which of these callback functions belongs to which case. If we show this again in the browser once the query executes we can see the same behavior we did before. If Github stopped working suddenly, this code wouldn't run, but the code that wrote out to the console that it failed would certainly do that and of course you would do something more interesting like setting some text in the UI to show that it was an error condition. Now that we have networking and manipulating the DOM and querying the DOM, let's bring it all together by making this form work to actually issue the query so that the user can actually enter a query in here and see the results.
-
Working With Forms
Now that we've seen jQuery work in a variety of ways let's put them together to make our form actually work. We'll use the querying pieces we've looked at, we'll look at the manipulating pieces we've looked at, and we'll use the networking all together to make our form work. To start out we want to handle an event on the actual form. So we go and look at our form in here, you remember the form is called class bordered image or simple form, but in our case we're going to want an id here because we only want to react to this code for this exact form. So let's call this our gitHubSearchForm. You can call it any other thing you want, but that'll do for now. And because it's an id we'll start with pound and find our form on the page and use on again to handle an event. And the event we're looking for is submit. So when the user submits the form we went to be able to handle it. Now if you remember from earlier we were actually handling it with this action out to this echo tool I have. So we don't want our form to actually do this execution anymore and one of the things you can do with an event handler is return false from it and it'll know not to let the event actually fire, that you're going to handle the event, but don't let the default behavior actually happen. It's very common when you're dealing with forms to not actually let the form execute because you may be displaying something new on a page like we're going to be doing or you may be validating the code on the page and in both those cases you don't want the form to actually submit and accept new data from the server and replace your page. You'll want it to be more interactive than that. Now that we're returning false, let's do something. In our case we want to actually execute this query. So when someone searches using the form and presses search we want this search to happen. So now that it's in here let's go ahead and look in the browser. We'll see that it doesn't execute this right away, but once we press search the execution happens. But we want to use this data from our form to compose the query. So we're going to need a couple pieces of information first. We're going to need the search phrase. We're going to get that by searching for the search phrase on the page, which is this input. And remember we named it search phrase so we'll just do #SearchPhrase and we're going to call a method called val. Val is going to take the result of that search page and return it here as the actual value that the user inputted. If the user hadn't inputted anything at that point it'll just return us an empty string. We're also looking for whether the checkbox was checked. And remember this input checkbox was called use stars, so we'll do the same thing. In this case because it's a checkbox it'll return us a Boolean and lastly we're interested in the language of choice and this was a select or a list box and the id there was lang choice. So we're going to do the same thing in using the id and call val again to get the language that was chosen. Now in our case we don't want to actually issue the search unless a search phrase was used. We just don't want to turn every result out there, so we have to have a search phrase. So we'll first just test for search phrase and if it is good we want all this code in here to run. We want to keep that return false outside of this if because we want it to shortcut the form submission in all cases, whether we're going to issue a search or not. And if we do want to do a search we're going to construct the URL that we're going to use for the search, but first let's use our existing result list here and let's clear it by setting its text to say performing search. Remember our network query is going to take us a minute so we want to show the user something while the search is happening. Now let's construct the query. Let's start by recreating this and we're going to copy all of it up to this q= because directly after the q= is going to be the actual search phrase we want to enter. And we're just going to add to this the search phrase. If our language choice doesn't equal all then we want to actually include the language choice. Remember in our list we have all as an option and then these other languages as other options. If they say all the Githib API says don't bother giving us a language, we'll just use all of them. So if it's not all we need to include this little piece, language and then the name of the language. So gitHubSearch and I'll just use += to append it to it because I'm following this pattern, plus language and then the name of the language. Finally, we'll include the use stars. So if they've told us to use the stars we'll do the same thing, we'll append to it, this last little bit of our URI. Now when we perform the search we'll be including the user input into the search. Let's see this working. When we refresh the page we're starting from nothing and if we do a plain old search nothing's going to happen, but if we include a search like nuget, it shows performing search and then when it completes, now that we're using our input we're getting the results exactly the way you would expect it. If we change the search to something like search engine we're going to get a whole different set of results. I said language C# and the language that's showing up here is C, something's wrong. If we look at our browser we'll see that the search engine is showing language C and in fact search engine has a $20 in the middle and this is on purpose actually. When we are constructing URI, the browser is trying to make sense of all the text we've put in that URI. So in our code we were simply taking whatever information was given to use by the user for search and language choice and embedding it in our project. The problem is certain characters like the pound sign are especially used inside of the web and so it doesn't know what to do with them. So we need to use a special function to make sure that these are okay for a URI or a URL. If we call encode URI component when we're adding it, we simply wrap the search phrase around encode URI component and we'll do the same for language choice. We'll see here back in the browser when we execute this search we're now getting language C%23, which is the encoding for 23. We're still getting the %20, which is the encoding for a space because that's the correct thing to do here. The space was fine in our search phrase, but if we search for something with other special characters we want them to be encoded into the URI correctly. So we're now getting results that are actually all C# the way we expected. We changed this to JavaScript, we'll get the JavaScript ones. And so we're actually getting results based on what the user actually wants and is interacting with the page in the way you would expect it to. Let's wrap up this module.
-
Summary
So we've talked about jQuery in this module, and tried to give you a taste of what it's capable of. We've seen that it's simply a JavaScript library for performing some basic tasks in web development. We've seen that you can include jQuery like any other library you might need. On it's face jQuery is about querying and changing the DOM, we can see we can do a lot more and really create rich interactive experiences with it. Because you're leveraging your CSS selector knowledge you can become better at jQuery and CSS at the same time. Of course interacting with the user is important, so allowing jQuery to help you manage events in web development means you'll be better at those quicker. And of course the networking we showed you in jQuery is really pretty simple to use. Looking at the way that jQuery queries the DOM, changes the DOM, can pull data out of the DOM as well as use the networking, you can create really interactive tools using jQuery and the web in pretty simple ways. So in this course we've tried to teach you the very, very basics of web development, just give you a taste of what the different pieces are and how they interact together to create great web experiences, but of course we know we've just barely scratched the surface. That's where the other courses at Pluralsight can really help you. jQuery can help you build interactive experiences, but learning a full framework in a data binding framework like Angular, Ember, or even Knockout can help you create richer single page applications that you could just by using jQuery. If you're new to JavaScript you might want to delve into the one of the JavaScript courses in the Pluralsight library to leverage your existing language to learn this new language called JavaScript. Likewise there are whole courses on understanding the depths of what CSS is capable of and I'd encourage you to look at those as well. Even jQuery can be expanded on with other courses in the Pluralsight library. So hopefully this quick start has helped you learn some of these basics and wet your appetite for learning more about web development because you've really just only started. Thanks for taking this course on jump starting your journey to being a web developer. My name is Shawn Wildermuth of Wilder Minds. Thanks for joining me.