Twitter Bootstrap for responsive, mobile first web apps

This blog is no longer updated. Please refer to my new account: http://sanderrossel.com

Welcome back! As you may know I’ve just finished my series on starting web development and it was a huge success! I’ve got a lot of good feedback, so thanks everyone. If you have no idea what I’m talking about you can visit the first part of my web development series here: Web development #1: Internet and the World Wide Web.
So to stay in the spirit of web development I decided to do some blogs on popular libraries and frameworks. This week I’m going for Twitter Bootstrap (from now on I’ll call it just Bootstrap).
Speaking of Twitter, I just created a Twitter account to share interesting articles and industry news, so be sure to follow me @sanderrossel.
I also got myself a GitHub account where I’ll upload the code files for my blogs. You can find my GitHub at https://github.com/SanderRossel. The files for this particular blog can be found at the bootstrap-blog repository.
Yes, I’m doing the best I can to serve your every programming needs!

Bootstrap basics

Now let’s talk about Bootstrap. Bootstrap is a free and open-source front end CSS and JavaScript framework developed at Twitter. It was first released as open-source in 2011, version 2 came in 2012 and currently we’re at version 3, which is also the version I’ll be using in this post. One remark on the Bootstrap versions, there’s quite a difference between Bootstrap 2 and Bootstrap 3. If you’ve already worked with Bootstrap 2 and want to migrate or have an overview of the differences you may want to have a look at the Migration guide at Bootstrap.
As you may have guessed you don’t need any server software to use Bootstrap, so I’ll keep the examples here simple so you really don’t have to do anything else than create some files and run them in your browser.

So what does Bootstrap actually do? Simply said it allows you to easily layout your page using classes and HTML attributes. It’s mostly just CSS. Bootstrap does this using a grid on your page. Not an actual HTML grid, but a virtual grid, containing twelve columns that you can use to divide your content. So it may look something like this.

An example of how your Bootstrap columns can be organized.

An example of how your Bootstrap columns can be organized.

And of course you can use any number of columns, up to twelve, on any row. So how did I do this? Let’s look at some HTML.

<div class="container">
    <div class="row">
        <div class="col-xs-12">12 columns wide</div>
    </div>
    <div class="row">
        <div class="col-xs-6">6 columns wide</div>
        <div class="col-xs-6">6 columns wide</div>
    </div>
    <div class="row">
        <div class="col-xs-8">8 columns wide</div>
        <div class="col-xs-4">4 columns wide</div>
    </div>
    <!-- etc... -->
</div>

Here you can clearly see how I define rows and columns to layout my page (more on that later). Your columns don’t have to add up to twelve. If you have less than twelve columns there’ll just be an empty spot on your page and if you go over twelve columns Bootstrap will simply wrap your excess columns on a new line (but it’s best if you avoid this). If you need more or less than twelve columns for your page you can download the LESS version of Bootstrap and edit the columns variable. Very cool, but I’m not discussing that here.
So here are a few rules, rows need to be inside a .container (for fixed width) or .container-fluid (for full width) for proper alignment and padding. You should place only columns inside your rows and content within columns.

Other than that Bootstrap adds theming to your website. There are a lot of themes, both free and premium, that you can use to give your website a complete new look without having to change your HTML. And Bootstrap has a lot of controls for HTML, like dropdowns, buttons, navbars, tabs, etc. We’ll look at some of them later.

Creating a responsive page

So now that we know what Bootstrap can do for us let’s put this into practice. First of all let’s look at a very basic Bootstrap document. You can actually get it from the Bootstrap site. I’ve removed some stuff from it (mostly comments) that we aren’t going to use (mostly backwards compatibility for IE). You can view the original basic template at Twitter Bootstrap – Getting started.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Hello, Bootstrap!</title>

        <link rel="stylesheet" href="css/bootstrap.min.css">
    </head>
    <body>
       <h1>Hello, Bootstrap!</h1>

       <script src="js/jquery-2.1.3.min.js"></script>
       <script src="js/bootstrap.min.js"></script>
    </body>
</html>

As you can see I’m assuming your HTML file is in a folder that contains a folder called css which contains the bootstrap.min.css file and a folder called js which contains bootstrap.min.js and jquery-2.1.3.min.js. You can get Bootstrap from the download section at Bootstrap and jQuery from the jQuery website. Bootstrap uses some jQuery for certain components, but you might not need it. If you do need it make sure you use a compatible version of jQuery. Other than that the meta element with the viewpoint may be unfamiliar to you. You should use this for websites that are optimized for mobile devices (don’t use it for non-responsive pages though).

So now that we have the basic Bootstrap template let’s display some text on the page. Let’s say we’re creating a news website and we want the cover story at the top and page wide. Beneath that we want some featured articles. And what’s more, we want it to look good on any device. So let’s say we have two rows, one for the cover story and one for the featured articles, that will be displayed next to each other. We can also safely assume that the number of featured articles that fit on the page is limited by our screen size. On a big screen we can have four featured articles next to each other, but on a medium and small sized screen we want maybe only three or less articles. Well, that’s something Bootstrap is really good at! So in the example above I’ve used col-xs-* to create a row that spans * columns. The xs here is the trick. It actually means that this row spans * columns on any device that’s xtra small (xs) or larger (because we didn’t specify what should happen if it gets larger). We have col-lg-* (large, anything larger than or equal to 1200 pixels), col-md-* (medium, anything larger than or equal to 992px), col-sm-* (small, anything larger than or equal to 768 pixels) and col-xs (extra small, anything smaller than 768 pixels). Most phones go into the xs category, tablets would be small or medium, laptops medium or large and desktops large. So then let’s see some HTML. For our news site we can have the following body (actual content left out).

<div class="container">
    <div class="row">
        <h1>Sander's bits</h1>
        <p>Writing the code you need</p>
    </div>
    <div class="row">
        <div class="col-xs-12">
            <h2>Main article</h2>
            <article><p>...</p></article>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-3 col-md-4 col-sm-4">
            <h3>First featured article</h3>
            <article><p>...</p></article>
            </div>
        <div class="col-lg-3 col-md-4 col-sm-4">
            <h3>Second featured article</h3>
            <article><p>...</p></article>
        </div>
        <div class="col-lg-3 col-md-4 col-sm-4">
            <h3>Third featured article</h3>
            <article><p>...</p></article>
        </div>
        <div class="col-lg-3 hidden-md hidden-sm">
            <h3>Fourth featured article</h3>
            <article><p>...</p></article>
        </div>
    </div>
</div>

Let’s figure this bit out, eh? First of all I’m using a container, or a div element with the .container class to hold my rows. One thing about the container is that it’s sized differently on different screen sizes. So next I’m creating a row to hold my page name, which is Sander’s bits. Then comes the second row with our cover story. It’s spanned out across all twelve columns on all devices. Now comes our third row, which is the most interesting. Each article has multiple classes, one for each device size that we want to cover. On large devices we display four articles, each spanning three (out of twelve) columns (.col-lg-3). On medium sized devices the fourth article gets hidden (using the .hidden-md class) and the other three articles now span four columns (.col-md-4). Small devices have the same layout as medium sized devices (.hidden-sm and .col-sm-4). On extra small devices we don’t specify any layout and our page will display the articles one under the other (including the fourth). You can test this by opening the page in your browser and then simply changing the size of your browser window. Check at what size your browser hides or displays the fourth article and at what sizes it places the articles under each other.
I admit that’s quite some classes on your elements, and it may take you a bit to figure out what’s going on, but you get a lot in return. I don’t know about you, but I find this pretty amazing!

Bootstrap classes

Our news website is starting to look pretty professional already, but we want the cover story to stand out a bit more. Bootstrap adds all kinds of classes that you can use to style your page. For our cover story we’re going to add two: .lead and .text-center.

<h2 class="text-center">Main article</h2>
    <article><p class="lead text-center">...</p></article>

You may have guessed, but there are also the classes .text-left and .text-right and all they do is align your text to the left, right or center.
Looking good, right?

Let’s ‘mute’ the tagline too, it’s not all that important, so we want it to be visible, but not stand out too much.

<p class="text-muted">Writing the code you need</p>

Now what kind of news website doesn’t have weather forecasts? Let’s add some! I’m thinking of adding an HTML table to the bottom right. It’ll show up under our third or fourth column (depending on screen size). Luckily we can use offsets for our columns in much the same way we can make them span multiple columns. So let’s have a look at that table. Notice that I’m using HTML 5, which means we need table, thead and tbody elements. So the following HTML goes at the bottom of our container.

<div class="row">
    <div class="col-lg-3 col-lg-offset-9 col-md-4 col-md-offset-8 col-sm-4 col-sm-offset-8">
        <h4>Weather</h4>
        <table>
            <thead>
                <tr>
                    <td>Day</td>
                    <td>C&deg;</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Today</td>
                    <td>30</td>
                </tr>
                <tr>
                    <td>Tomorrow</td>
                    <td>25</td>
                </tr>
                <tr>
                    <td>Day after tomorrow</td>
                    <td>27</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

So the table is positioned right across all devices. The .col-lg-offset-*.col-md-offset-* and .col-sm-offset-* work great (and of course there’s also a .col-xs-offset-*). I don’t need to explain this, because you already know how it works. The table itself is rather clumsy though. The columns are pushed against each other and it doesn’t scale well at all. Bootstrap has a really very simple solution, just add the .table class. And because we want some additional styling we’re also going to add the .table-striped and .table-bordered classes.

<table class="table table-striped table-bordered">

Very nice! Now in that same style I also want to add some stock information on our page. And let’s indicate whether a stock went up, down or stayed the same. We can do this using the .success, .danger and .info classes (there’s also .warning and .active). These classes can be applied to buttons, text, table rows, labels, etc. The Bootstrap team has actually made sure these classes are consistent across elements for Bootstrap 3. So without any further explanation here’s our stock table (I just made up the numbers, don’t buy or sell based on this table).

<div class="row">
    <div class="col-lg-3 col-lg-offset-9 col-md-4 col-md-offset-8 col-sm-4 col-sm-offset-8">
        <h4>Stock</h4>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <td></td>
                    <td>Price</td>
                    <td>%Change</td>
                </tr>
            </thead>
            <tbody>
                <tr class="success">
                    <td>Dow</td>
                    <td>18,128</td>
                    <td>0.94%</td>
                </tr>
                <tr class="danger">
                    <td>Nasdaq</td>
                    <td>5,026</td>
                    <td>-0.69</td>
                </tr>
                <tr class="info">
                    <td>S&P 500</td>
                    <td>2,108</td>
                    <td>0.00</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

So again, this is pretty simple, but the effects are amazing.

Let’s add an image to our main article to make it stand out even more. Bootstrap has some classes to handle images. Now what is the internet all about? If you answered cats you’re right! So let’s add a picture of my parent’s cat. We can add some classes to make it look good and have it scale with our screen size. I’m going to add the class .img-circle to make it round (alternatives are .img-rounded for round corners and .img-thumbnail). I’m also adding .img-responsive so it will resize with my screen. Last, but not least I’m adding the .center-block class to, well, center it.

<h2 class="text-center">Main article</h2>
 <article>
 <img src="http://sanderrossel.com/wp-content/uploads/2015/03/Cid.jpg" alt="My cat, Cid!" class="img-responsive img-circle center-block">
 <p class="lead text-center">...</p></article>

Bootstrap components

At this point you have to look pretty hard to see if you’re looking at the New York Times website or at our Bootstrap example page because our page is looking so good and professional. I’m still not completely happy though. I want my weather forecast and stock information to be tabbed. I’ve given an example of this before using jQuery UI in a previous blog post, Web development #6: Getting interactive with JavaScript, but this time we’ll be using Bootstrap to get the same effect. As mentioned before Bootstrap needs jQuery for certain components, the tab control is one such component. Compared to jQuery UI Bootstrap has some pros and cons. The pro is that we don’t need to write a single letter of JavaScript. The con is that the HTML is rather, well, bloated. You can remove the entire row containing the stock table and add the stock table to the row with the weather table. Then we need to tab both tables. So let’s look what it looks like.

<div class="row">
    <div class="col-lg-3 col-lg-offset-9 col-md-4 col-md-offset-8 col-sm-4 col-sm-offset-8">
        <ul class="nav nav-tabs">
            <li class="active">
                <a href="#weather" data-toggle="tab">Weather</a>
            </li>
            <li>
                <a href="#stock" data-toggle="tab">Stock</a>
            </li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane active" id="weather">
                <!--Weather table goes here-->
            </div>
            <div class="tab-pane" id="stock">
                <!--Stock table goes here-->
            </div>
        </div>
    </div>
</div>

So like with jQuery UI we need an unordered list with the .nav and .nav-tab classes and anchor tags that link to the id’s of some div elements. The div elements containing our tab pages go into another div element that has the .tab-content class and is placed directly under the tab list. The data-toggle attribute tells Bootstrap what kind of component this is, a tab. Another cool feature are the tab pills and vertical tabs. Try changing the .nav-tabs class into .nav-pills or .nav-stacked. Looking pretty good!

Finally, let’s add a menu to our page. Adding a menu to any website can be pretty difficult. It needs to stay at the top, it needs to scale, you want some components to be left-aligned, others right-aligned, it’s just quite difficult. Bootstrap makes it a lot easier, but even then it’s not exactly easy. You need lots of classes, lots of elements, and just lots of everything really. It’s still easier than doing everything yourself and it scales really nice. So here’s what I’ve done. I’ve taken the example from the Bootstrap website and I’ve stripped it a bit. I’ve removed some buttons and dropdowns and some HTML attributes and classes that have to do with accessibility (for people with disabilities, like bad sight or even blindness).
We can create a navigation bar using the nav element. Within this nav element we’re going to create a fluid container, meaning it spans our entire page. After that we’re going to specify what our menu looks like when it’s collapsed, for example on phones, and what elements we like to show. So how about our brand, for which Bootstrap has some special classes, a search form, an About link and a Login button? The HTML would look like this (placed directly under your opening body tag).

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="http://sanderrossel.com" target="_blank">Sander's bits</a>
        </div>

        <div class="collapse navbar-collapse" id="menu">
            <form class="navbar-form navbar-right" role="search">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Search">
                </div>
                <button type="submit" class="btn btn-default">
                    <span class="glyphicon glyphicon-search"></span>
                </button>
            </form>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">About</a></li>
                <li><a href="#">Login</a></li>
            </ul>
        </div>
    </div>
</nav>

So check that out and look what happens when you resize your browser window. Awesome!

I’ve also used a glyph icon in my search button. This is another Bootstrap goodie. You can use glyphs like that to make your page just a little prettier. Actually, I want that for my weather and stock tabs too. Let’s change that.

<ul class="nav nav-tabs">
    <li class="active"><a href="#weather" data-toggle="tab"><span class="glyphicon glyphicon-cloud"></a></li>
    <li><a href="#stock" data-toggle="tab"><span class="glyphicon glyphicon-stats"></span></a></li>
</ul>

Nice, right?

There’s lots more that Bootstrap has to offer. We’ve already seen quite a bit and we got some pretty amazing results. The best part is that we got those results without writing a single line of JavaScript! What else can Bootstrap do? Well, it has more classes you can use to style your elements, like Code, Forms and Buttons. It has more components you can use, like Buttongroups, Button dropdowns, Breadcrumbs, Page headers, Alerts and Progress bars. And if you don’t like how your website looks try one of these free Bootstrap themes or check out these premium Bootstrap themes. If you like to know more about Bootstrap I can recommend two free books by SyncFusion, Twitter Bootstrap Succinctly (which is about Bootstrap 2) and Twitter Bootstrap 3 Succinctly (which is both an update and an addition to the first book).

You can find the entire HTML for this blog and the necessary CSS and JavaScript files on my GitHub account in the bootstrap-blog repository.

Happy coding!

Web development #6: Getting interactive with JavaScript

We’ve come pretty far by now! We’re almost there actually. After reading this post you should be able to create pretty awesome websites using the full web development stack! So what’s left for us to discover? We have seen we can build dynamic websites on the back end using PHP, but what about being dynamic once the page is loaded? Well that’s where JavaScript comes into play!

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

The websites we’ve build were all pretty amazing. We’ve started simple using just HTML, added some CSS, then we added some dynamic content and we could even upload our own content. I don’t know about you, but I think that’s pretty amazing. However, I still feel like our pages are missing a little… schwung! How about highlighting buttons, sliding content in and out of our page? Just some fancy visuals that will make our website stand out. JavaScript comes to the rescue.
As an added bonus we can make calls to our back end without refreshing the entire page using AJAX. More on that later, let’s look at some fundamentals first.

JavaScript fundamentals

JavaScript has been around since 1995. It’s easy to learn, but hard to master. I’m not going to spend a lot of time on the syntax because it looks (and behaves) a lot like PHP, including truthy and falsey). I’m just going to write code. Try to keep up. I’m still writing in Notepad++ by the way. We also won’t be needing XAMPP to run basic JavaScript in this post (we’ll be needing it later for AJAX though).

One thing you should know about JavaScript is that, like CSS, it can be embedded into your HTML. But we don’t want that. In my post about CSS we learned to keep HTML and CSS seperated, which makes it easier for you to remodel your page by simply replacing some CSS files. We’ll use the same approach for JavaScript.

So let’s take a look at our first example. Yes, it’s going to be Hello world! Not the most exciting example, but you’ll see JavaScript in action. So we start out by creating a very simple HTML file. Call it whatever you like.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first JavaScript!</title>
        <script type="text/javascript" src="MyJS.js"></script>
    </head>
    <body>
        <button onclick="sayHello();">Press me!</button>
        <p id="output"></p>
    </body>
</html>

And now in the same folder create a file called MyJS.js. Inside it put the following code:

function sayHello () {
    var output = document.getElementById('output');
    output.innerHTML = 'Hello JavaScript!';
}

So let’s look at both the HTML and JavaScript. First in the header of the HTML you’ll notice I’ve added a script element. In this element I define the type and src attributes. Pretty straightforward I think. Your HTML now simply loads the specified JavaScript. In an actual server-client environment this means that the JavaScript files are sent to the client together with the HTML page.
Other than that we see a button element with an onclick event. Now whenever the user presses a button an event fires. An event is simply a notification you can subscribe to. In this case we subscribe by specifying onclick and telling it we want the function sayHello to be executed.

Now this function, sayHello, is defined in our MyJS.js file. It does the following. We declare a variable called ‘output’ using the var keyword. We assign it the result of a function called getElementById that takes a string as input parameter and is defined on something called document. Now your document is a variable that your browser gives to you and it represents your HTML content. So we’re almost literally saying “document, give me the element with id ‘output'” and guess what it returns? Yes, our p element with id ‘output’! Now that we have our paragraph we can alter it any way we see fit. In this case I’m simply going to give it the text “Hello JavaScript!”.
There’s more functions like getElementById, like getElementsByName() and getElementsByClassName(). Once you have an element you can get its child elements (using children()), its parent element (using parentElement()), its ‘neighbouring’ elements (using previousSibling() and nextSibling()) and much more. What we’re basically doing is traversing and altering the DOM (Document Object Model, or your HTML document).

Now here’s why I like and dislike JavaScript. It took me about fifteen minutes to get this example running… Fifteen!? Yes. Why? Because I spelled ‘innerHTML’ as ‘innerHtml’ and what does JavaScript do? You might say it gives us an error saying innerHtml does not exist. Wrong, what it actually does is create innerHtml on the ‘output’ variable (or more precisely the object it references). It doesn’t do anything with it, it just sits there. But in the meantime innerHTML remains empty, my page doesn’t show “Hello JavaScript!” and I’m not getting an error of any kind.
So with JavaScript you can actually alter already existing objects! How cool is that? Pretty cool, but it can lead to very subtle and hard to troubleshoot bugs, so be careful. That is also why you should always use the var keyword when creating variables. Failing to do so will work fine, but will actually create a property on your this object (the object, or context, you’re currently operating in).

And that’s actually all I’m going to tell you about basic JavaScript. The standard library is actually pretty difficult to work with and you’ll often deal with bugs like the one I just described. To top it off different browsers can behave differently using the same JavaScript code. Luckily (and also a bit unlucky) there are literally thousands of libraries and frameworks that do all the hard stuff for us. One of those libraries has become so popular that it has become the de facto standard when working with the DOM, I’m talking about jQuery.

Getting started with jQuery

There are two ways to get jQuery included in our page. One we have already seen. We get the jQuery files from jQuery.com, put them on our server (or during development our local machine) and get them in our page using the HTML script element. There are two versions you can get, the regular or the minimized version. The regular version is great for development as it is easier to debug. The minimized version has all unnecessary characters like spaces, meaningful variable names, white lines etc. removed from the file, making them practically unreadable, but making the file a little smaller in size making it to load a bit faster on our webpage. A lot of libraries have regular and minimized versions.

For this example we’re going to use the second method to get jQuery in our page though, which is through a CDN, or Content Delivery Network. A CDN is just some host providing you with popular files you might need, like jQuery. A possible benefit of using a CDN is that they might have servers across the globe, which means that if someone in America is using our website hosted in Europe they could still get jQuery from a server near them. Another possible benefit is that you don’t have to host the file yourself. So if you can, use a CDN.
Popular CDNs are Microsoft and Google, so let’s go with the Google CDN.
One word of caution though. Whenever your website requests a file from any CDN the host of that CDN may track the users of your page (they’re making a request after all). So while this is probably no problem for your personal website, it may be an issue for corporate environments where privacy and security are of bigger importance.

Let’s have a look at how our header looks with jQuery from a CDN.

<head>
    <meta charset="utf-8">
    <title>My first JavaScript!</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript" src="MyJS.js"></script>
</head>

So you see, it actually looks the same, but we’re putting a link in the src attribute. Also notice that I put jQuery above MyJS because MyJS is going to need jQuery to run. Now let’s rewrite that sayHello function we had so it uses jQuery.

function sayHello() {
    var output = $('#output');
    output.text('Hello jQuery!');
}

Looks weird? $ is actually a perfectly valid function name in JavaScript and jQuery is utilizing it. $ is also called the jQuery function and alternatively you could’ve used jQuery(‘#output’). Now notice what we pass as a parameter to the jQuery function. It’s a CSS selector! Yes, you can get ANY element (or elements) on the page using CSS selectors. That’s great because we already know CSS. And when we have our output element we set the text (the part between the opening and the closing tags) to ‘Hello jQuery!’.

Now remember that I said we shouldn’t have JavaScript in our HTML? Well, we still have our onclick event in the button tag, so I guess I lied. JavaScript doesn’t really have a simple elegant solution to this problem. But jQuery does (they made it simple)! First of all let’s change our button tag so it doesn’t hard wire that onclick event.

<button id="btn">Press me!</button>

And next let’s take a look at our JavaScript.

$(document).ready(function () {
    $('#btn').on('click', sayHello);
});

function sayHello() {
    var output = jQuery('#output');
    output.text('Hello JavaScript!');
}

As you can see I’ve added a $(document).ready(function) call to our JavaScript page. That might look arcane, but it’s really simple actually. We call the jQuery function and pass it our document. We’re getting something back which obviously has a ready function that takes a function as parameter. This function, also called a callback function, is called when the document is ready (the HTML has loaded and is ready for traversal and manipulation). We then create an anonymous function to be called. It’s really the same as our sayHello function, except that we don’t give it a name. So in this anonymous function we get our button element and then call the on function on the result. With the on function we can hook up events to our elements. In this case we want the click event and we specify a function to be called when the click event fires (the button is clicked).
Here’s an alternative way of writing the above. I’m using a shorthand notation for $(document).ready by simply passing an (anonymous) function directly to the jQuery function.

$(function () {
    $('#btn').on('click', function () {
        $('#output').text('Hello jQuery!');
    });
});

Let that sink in. Study the syntax and compare the two examples. Take a look at how I rewrote the sayHello function to an anonymous function in particular, it may help understanding what’s going on. You may also want to try rewriting this using no anonymous functions.

There’s a whole lot to jQuery that I cannot show you in this blog, but the jQuery documentation is actually pretty good, so be sure to use it!

Now I’m going to show you another trick with which you can create beautiful pages using classes and CSS. First create a CSS file called MyStyle.css and add the following style to it:

.hovering {
    color: white;
    background-color: blue;
}

Now let’s create a single paragraph we want to light up once you hover your mouse over it. Don’t forget to link your stylesheet!

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first JavaScript!</title>
        <link rel="stylesheet" type="text/css" href="MyStyle.css">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="MyJS.js"></script>
    </head>
    <body>
        <p id="p">Try hovering over me!<br>
        An extra line<br>
        so it's easier<br>
        to hover...</p>
    </body>
</html>

Nothing special there. Now for our JavaScript:

$(function () {
    $('#p').hover(function () {
        $(this).addClass('hovering');
    }, function () {
        $(this).removeClass('hovering');
    });
});

So we get out p element and then call the hover function which takes two functions as input. One function is called when your mouse enters the paragraph and the other function is called when your mouse leaves the paragraph (moving your icon over an element is called hovering). Now in this function we call the jQuery function and pass it this. The this keyword is a little difficult in JavaScript. This is the context in which you are currently operating, so this can refer to the window object (the ‘general context’), to an object in which you are currently operating, or in this case the HTML element on which the hover event is fired. So when we pass the p element (this) to the jQuery function we get a jQuery object on which we can call jQuery functions, such as text or addClass and removeClass. So we’re dynamically adding classes. But since our CSS applies a certain style to those classes we now get dynamic styling on our page!

jQuery UI

I want to show another quick example of how powerful JavaScript, and jQuery in particular, really is. For this we’re going to need jQuery UI. Another library that’s made by the jQuery people and uses jQuery, but adds functionality specifically for your UI (User Interface). Next to a JavaScript file the jQuery UI library makes use of a CSS file too. We can get both from the Google CDN we’ve used earlier. So here is the HTML. It looks large, but it’s quite simple.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first JavaScript!</title>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
        <script type="text/javascript" src="MyJS.js"></script>
    </head>
    <body>
        <div id="accordion">
            <h3>Page 1</h3>
            <div>
                <p>Some content...</p>
            </div>
            <h3>Page 2</h3>
            <div>
                <p>More content...</p>
            </div>
            <h3>Page 3</h3>
            <div>
                <p>Lots of content...</p>
            </div>
        </div>
        <br>
        <div id="tabs">
            <ul>
                <li><a href="#page1">Page 1</a></li>
                <li><a href="#page2">Page 2</a></li>
                <li><a href="#page3">Page 3</a></li>
            </ul>
            <div id="page1">
                <p>Some content...</p>
            </div>
            <div id="page2">
                <p>More content...</p>
            </div>
            <div id="page3">
                <p>Lots of content...</p>
            </div>
        </div>
    </body>
</html>

And now for some amazingly difficult JavaScript…

$(function () {
    $('#accordion').accordion();
    $('#tabs').tabs();
});

So check out the result with and without those two lines of JavaScript. You’ll be amazed! And that’s the power of JavaScript.

So in this post we’ve become familiar with JavaScript and jQuery. You can build amazing websites using JavaScript. There are literally thousands of JavaScript (and CSS) libraries and frameworks. Some, like jQuery, are pretty all-round, but some are really specific about doing one particular thing. In a later blog post I’ll point out some of the more popular ones.
Try to play around a bit with JavaScript. We’ve only scratched the surface. I haven’t even mentioned prototype, which is vital in fully understanding JavaScript. You can start getting your JavaScript skills up to date with a free ebook from SyncFusion: JavaScript Succinctly. Now as luck would have it there’s also a free jQuery ebook from SyncFusion: jQuery Succinctly. So I recommend creating a free account and downloading these sweet free resources (and no, I’m not affiliated with SyncFusion, I just like the Succinctly series).

JavaScript also adds functionality to get data from or send data to our server without having to refresh our entire page. This technology, called AJAX, is what I will talk about in my next blog post.

Stay tuned!

Web development #5: User input with HTML Forms

In my last blog post we’ve seen how to create dynamic web pages using PHP. The examples in this post are using the code examples from that blog post, so if you haven’t read it I suggest you do. You can find my other posts here:

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

In the last post we created a page that would show movies (or music, or whatever) based on a simple text file (because I’m not covering databases). You could simply add new lines to the text file and they would show on your page (after a refresh). But now you probably want to add new lines directly from your website and not in the file. Why would you want that? Well, for example, because your users don’t have access to your file (and rightfully so)! Also because your web interface is more user friendly than direct file access. When you’re going to implement an actual website you’ll probably be using an actual database and you’ll be working with more data than just lines in a file. You may want to ask users for their name, address, gender, password, for webshops you want to know their preferred shipping and payment methods. And of course you want users to add content to your site, like blogs, product reviews, messages, etc. There’s plenty of cases where you’d want user input!

So we have basically two options: HTML Forms or AJAX calls. AJAX calls are discussed in a later blog post, so in this one I’m going to focus on HTML Forms.

What are forms?

Forms are actually just a couple of HTML tags! <form></form> with some input tags, <input /> of which one has the type submit, <input type=”submit” />. Sounds easy, right? After all, you want your users to fill out a (digital) form where they give their input and then submit it to the server. How does this look?

<form action="MySite.php">
    <input type="text" name="name" />
    <input type="submit" />
</form>

Is it that easy? Almost! There are quite a few input types, such as checkboxes, radio buttons, date pickers and file pickers. We’ll look at some of them a bit later in this post. First let’s see what happens in the above HTML.

Save the above code in a file called MySite.php in your xampp htdocs folder. Now if you’d view this page you would see a field for the user to add text and a button saying “Submit” (it actually says “Verzenden” on my browser, which is the Dutch translation for “Submit”). Now what happens when you type in your name and click the submit button? You’ll be redirected to the site localhost/MySite.php?name=Your+name, which simply shows the same page again (because it was specified in the action attribute), but with your input emptied. You may not have noticed, but the entire page refreshed when you hit submit. The part behind the questionmark was added by the form and it contains the names and values of the input tags you have in your form tags. Now here’s the deal. You can actually get these values from your PHP code!

Now change your code to the following:

<?php
    if (isset($_REQUEST['name']))
    {
        echo $_REQUEST['name'];
    }
?>
<form action="MySite.php">
    <input type="text" name="name" />
    <input type="submit" />
</form>

Now what happens when you fill out your name and hit submit? Your name is being printed at the top of the page. But what’s happening in the code? Well, notice the isset($_REQUEST[‘name’])? PHP has some ‘superglobal’ variables. They’re variables that are visible in all your PHP code. $_REQUEST is one of them and it’s an array that contains any parameters that are send to your page. In this case we’re checking if the ‘name’ item was set. If it isn’t (when you first load the page) it does nothing. When it is (after a submit) we echo the value of ‘name’.

Notice that the action attribute of the form element indicates what page to navigate to. In this example I’m navigating to the page we’re already on, but it could’ve been any page. For example, try the following:

<form action="http://www.google.com/search">
    <input type="text" name="q" />
    <input type="submit" />
</form>

This will successfully open Google and search for your requested search term (Google uses ‘q’ for their parameter name).

GET and POST

So that’s the short version of it. The next thing you need to know is that in the previous examples we used the HTTP method GET to retreive our pages. Perhaps you remember from the first article in this series that GET is used to request a file from the server. In this case we requested the current page with parameter ‘name’ and we requested Google/search with parameter ‘q’.

Now what if we wanted to store information? We could use GET, sure. After all we simply send some data to our server where PHP can do with it what we want, right? All true, but that’s not always what we want. Suppose you want to save someone’s contact details. Would it look good in this huge URL http://www.mysite.com?name=sander+rossel&country=netherlands&address=…? No, it wouldn’t. Besides, your URL has a max length, so it won’t always work either.
Second, there is some data that you don’t want to send twice. What if someone was about to pay and they hit the refresh button (or even the back button)? Navigating to yourpage.com?payment=… would simply handle the payment again!
Last, there are some safety issues with GET. URL’s are stored in your browser history and on the server in plain text. Imagine sending your password like that! http://www.mysite.com?password=123456. Right, so is there another way? Yes, there is!

Whenever you want to send data to your server for storage, or data that is a bit more sensitive we can use the HTTP POST method. Let’s look at our first example again.

<?php
    if (isset($_REQUEST['name']))
    {
        echo $_REQUEST['name'];
    }
?>
<form action="MySite.php" method="POST">
    <input type="text" name="name" />
    <input type="submit" />
</form>

Wow, all I did was add the method attribute to my form element and assigned it the value of POST (method is GET by default). Now if you run this you’ll see your name on top of the page again (after a submit), but your URL will simply be MyPage.php. And try refreshing the page, your browser will warn you that information might be re-submitted.

PHP has specific superglobal variables for handling GET and POST variables specifically. They’re $_GET and $_POST, so you can use them instead of $_REQUEST (which has both GET and/or POST variables).

Other input

So we can now send some text input to the server. Surely you want more than that! Let’s look at some other input types. We’ll also tidy up our form a bit by using the label element.

<form action="MySite.php" method="POST">
    <label for="name">Name</label>
    <input type="text" name="name" id="name" required /><br><br>
 
    <label for="male">Male</label>
    <input type="radio" name="gender" id="male" value="male" checked /><br>
    <label for="female">Female</label>
    <input type="radio" name="gender" id="female" value="female" /><br><br>
 
    <label for="email">Email</label>
    <input type="email" name="email" id="email" /><br>
 
    <label>Receive newsletter
        <input type="checkbox" name="receiveNewsletter" checked /><br><br>
    </label>
 
    <label>Date of birth
        <input type="date" name="dateOfBirth" /><br><br>
    </label>
 
    <label for="avatar">Avatar</label>
    <input type="file" name="avatar" id="avatar" accept="image/*" /><br><br>
 
    <input type="submit" />
</form>

So that’s quite something. First, notice the <label> tags. I’m using them in two different ways. The first is to just declare them and associate them to an input field by specifying the for attribute and giving it the value of the id of the input I want to associate it with. The second way is by wrapping the input tags inside the label tags. Both ways are fine. Now if you click on a label the input gets focus or is selected/unselected. Nice!

Now for the different input types. We’ve seen the text type, so I’ll skip that one. I did add the required attribute though. Try submitting your form without filling out your name. There are more attributes like this one like max, maxlength, min and pattern.

Next is the password type. It looks very much like the text type, but if you type in it you get to see password characters rather than text.

Then comes the radio type. Notice I have two radio types, male and female. Also notice they have the same name. That means that if a radiobutton with a certain name is selected all other radiobuttons with the same name are unselected. In this case that means we can pick either male or female, but not both. I’ve also used the checked attribute for the male input. You don’t have to specify a value for checked. It will simply make this radiobutton checked. You could specify checked for both male and female, but your browser is only going to select one. It also makes for invalid HTML, so just don’t do that.

Following we see the email type. Again, looks like the text type, but if you commit your form your browser will check if the email address has valid syntax. That’s great, but don’t forget to check on the server too! Email is new in HTML 5 and will behave like text on older browsers.

Moving on we see the checkbox type. Not much to say, except that you can specify checked to have it checked, or omit it to have it unchecked.

Next is the date type. The user can pick or enter a date. The browser will validate if it’s a valid date (no 32st januari, etc.). This one is new in HTML 5 too and will also behave like text on older browsers.

Last, but not least, is the file type. You can use this to have a user select one or more files (if you need more than one simply add the multiple attribute, much like checked).

And of course you can handle all of those in your PHP code too. But I’m sure you can figure that out. There are other input types too, but I’ll leave it up to you to check them out. Just Google for HTML input.

Completing our example

So at this point we want to make our favourite movies example from my following blog work. Actually all we want to do is POST a movie title, add it to our text file and display it on our page. There’s actually a bit more to it than you might think… Here’s the complete code for the page.

<?php
    if (isset($_POST['movieName']))
    {
        $movieName = $_POST['movieName'];
        if ($movieName)
        {
            file_put_contents('movies.txt', htmlspecialchars($movieName) . "\r\n", FILE_APPEND);
        }
 
        header('Location: ' . htmlspecialchars($_SERVER['REQUEST_URI']));
        exit();
    }
?>
<!DOCTYPE html>
<html>
    <?php
        function fileAsUnorderedList($fileName, $notFoundMessage)
        {
            if (file_exists($fileName))
            {
                echo "<ul>";
                $lines = file($fileName);
                foreach ($lines as $line)
                {
                    echo '<li>' . htmlspecialchars($line) . '</li>';
                }
                echo "</ul>";
            }
            else
            {
                echo $notFoundMessage;
            }
        }
    ?>
    <header>
        <title>My favourite movies!</title>
        <meta charset="utf-8">
        <meta name="description" content="A list of my favourite movies.">
        <meta name="keywords" content="Favourite,movies">
        <meta name="author" content="Sander Rossel">
    </header>
    <body>
        <h1>My favourite movies!</h1>
        <p>
        <?php
            fileAsUnorderedList('movies.txt', 'No favourite movies found!');
        ?>
        </p>
        <h2>Add a movie!</h2>
        <?php echo '<form action="' . htmlspecialchars($_SERVER['REQUEST_URI']) . '" method="POST">' ?>
            <label for="movieName">Movie name</label>
            <input type="text" name="movieName" id="movieName" />
            <input type="submit" />
        </form>
    </body>
</html>

So that’s quite a lot! No worries. First of all you should notice that I’m handling our POST input. If movieName is set and it has a value (it’s truthy) we append it to our text file, followed by a new line (\r\n, or “line feed, carriage return” from ye olden days when we used typewriters).
What happens next is that we redirect to the current page using $_SERVER[‘REQUEST_URI’], another superglobal variable in PHP. So once we submit form data we get to our page with POST data. We handle the POST data and again load our page, but this time without POST data (a GET). If we wouldn’t do this we’d get an annoying pop-up every time we wanted to refresh our page. This technique is called the Post/Redirect/Get Design Pattern.

But there’s more happening. I’m using a function called htmlspecialchars, what’s that all about? Well, here’s a little practice for you. Remove all the htmlspecialchars from the code and add the following movie “<script>alert(‘hacked!’);</script>“. Now if you refresh the page you’ll get a popup saying “hacked!”. Quite annoying isn’t it? See it this way, people are going to submit text to your page and you’re going to echo that text as-is. But that text may be/contain valid HTML (and script)! And that would mess up your page or worse! It’s a huge security risk also known as Cross-Site Scripting or XSS. Now put the htmlspecialchars back in place and your page will simply display a movie with a rather weird name. So that’s what htmlspecialchars does. It makes sure your text is transformed into non-HTML, so > would be  echoed as &gt; etc. I’ve used this trick in a few places.

In our form elements I’m using the same tricks. I use $_SERVER[‘REQUEST_URI’] and htmlspecialchars. Why the $_SERVER[‘REQUEST_URI’]? If the name of your PHP file changes so would the URL to access it. If the URL was hard coded you’d have to check your PHP file and change all references to ‘movie.php’ to ‘myNewFileName.php’. With this trick we’ve got that covered!

A last remark on the PHP above the !DOCTYPE tag. Is this bad? Nope. Remember that all this PHP code is executed on the server and that your HTML is sent back. So by the time this file reaches your browser it has no knowledge of any code above !DOCTYPE.

Other than that you should know all the other stuff I’ve put in there. So now you have a website that actually takes user input, stores it on the server and serves that data back to the user. In the next blog we’re going to take a look at JavaScript, or code that runs from the browser! Good stuff.

Stay tuned!

Web development #4: PHP in the back

Missed me? It’s been a while since I last blogged (about three months). I’ve been busy moving to my own house and getting up-to-speed at a new job. Lots of good stuff, but no blogging. Well today is the day I’m picking this up again and I’m just going to act like it’s three months ago and continue with the series.

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

So in the previous installments we’ve created a web page using HTML and CSS. We can actually build pretty nice websites using just those, but we still run into some trouble. What if we wanted to add content to our site? We’d have to edit our HTML each time. What if we wanted to display our website in multiple languages? What if we wanted users to be able to add content to the site (such as a blog)? In other words, we want our content to be dynamic. That’s all not possible using just HTML and CSS. We’re going to need a bit more. We’re going to need something creating our HTML on the back-end.

For this blog post I assume you are familiar with HTML and CSS, which you can read about in my previous blog posts, and that you’ve worked with some programming language before, preferably some C-based language such as C# or Java.

Introduction to PHP

So our back-end is just a server listening for requests. Whenever a request comes in we want to handle it and send a response (such as an HTML web page). We can handle these requests with a variety of tools and languages, but for this article I’m using PHP.

Why PHP? First of all it’s free. Second, it’s one of the most popular web languages that has been around for a good long while. It has a huge community and lots of documentation and tutorials. Third, virtually all web hosts, even the free ones, have support for PHP. Other languages, such as C#, are not always supported. Last, but not least, PHP is quite easy to learn because it can be pretty lightweight. Actually I’m simply going to write my PHP in Notepad++.

So PHP was created twenty years ago, in 1995, by Rasmus Lerdorf. Back then the PHP stood for Personal Home Page. They changed it to PHP: Hypertext Preprocessor, making it a recursive acronym (because the first P stands for PHP, of which the first P stands for PHP, of which the first P…). Clever, huh? Anyway, PHP is a scripting language, meaning it is interpreted rather than compiled. It’s also procedural, object oriented, weakly typed and it has C-based syntax. Enough talking, let’s code!

Setting up your environment

Unfortunately we can’t code just yet. Remember that your browser renders HTML and CSS. It can also run JavaScript (which I will discuss in another blog post), but it can’t execute PHP files. Usually your server handles PHP execution. Chances are you don’t have a web server laying around. Luckily you can configure your own PC to act as a web server.

To do this simply install web server software. You have a few choices, but I’m going for XAMPP. You can download XAMPP here and then simply install it (choose all default options, or change them if you know what you’re doing). When the installation is done XAMPP will ask you to start the XAMPP Control Panel. Start it and you’ll see a list of options. We’ll need Apache, so just start it. Now start your favourite browser and navigate to http://localhost. You should see a XAMPP page. Congratulations, you have just installed a (local) web server and you can now run PHP files!

To check if it really works create a new text file and name it “hello.php”. Inside the file place the following text:

<?php
    echo "Hello, PHP!";
?>

Now go to the installation folder of XAMPP (you can go there quickly by using the ‘Explorer’ button in the XAMPP Control Panel), find the htdocs folder and place your hello.php file there. Now, in your browser, navigate to http://localhost/hello.php. You should see the text “Hello, PHP!” And now that we’ve got the mandatory Hello world example out of the way let’s start writing some real PHP.

Learning the syntax

So let’s first look at some basic PHP syntax. Basically you’re going to write an HTML page with some PHP in it. The PHP is going to create some text representing more HTML. To indicate that you’re going to use PHP use the <?php open tag and to indicate that you’re done with PHP use the ?> closing tag. You’ve seen this in the example earlier.

The echo, or alternatively the print, statement outputs your code to HTML. In the above example it creates the HTML “Hello, PHP!”, which is just some text. But we could make that echo “<h1>Hello, PHP!</h1>” and we would get a header on our page.

So as I mentioned PHP is weakly, or loosely, typed. That doesn’t mean PHP doesn’t have types, it means a variable can change its type while the code executes. It also means you can add 3 to “3” and the result might be 6 or “33”, so a bit of caution is required when working with weakly typed languages (and in fact PHP always converts text to numeric when adding).
So what are the types in PHP? First we have the int for numerics without fractional components (so 1, 8, 42 and 986 are valid integers, 1.12 is not). Second there is float, or double, for numerics with fractional components. Then we’ve got the boolean or bool for a simple true or false. Next is the string for text (or an array of characters). Then we’ve got the array, or a 0-based indexed collection of stuff. There’s the object type, which encapsulates state and behaviour. And last, and actually pretty literal least, there’s NULL indicating the absence of any value.
Nothing special if you’ve worked with other languages before.

So how do we go about and use these types? Usually we’d want to store them in variables. So how do we declare variables? We actually don’t… Just assign a value to some variable and all of a sudden it’ll be there. It’s a kind of magic! And a variable always start with the $ sign. The typical variable declaration then looks like this:

$intVar = 42;
$floatVar = 3.142;
$boolVar = true;
$stringVar = "Some string"; // Double quotes.
$stringVarAltern = 'Alternative string'; // Single quotes.
$arrayVar = array('Pulp Fiction', 'Fight Club', 'Star Wars');

class person
{
    public $name = NULL;
    public $age = NULL;
}

$objectVar = new person();
$objectVar->name = 'Sander';
$objectVar->age = 27;

$nullVar = NULL;

Now aside from the class and objectVar that looks pretty straightforward right? But beware, the following is completely legal (PHP is weakly typed, remember?):

$stringVar = 'Some string';
$stringVar = 42;

Now that’s something you do want to look out for.
There’s something else about strings too. See how you can declare a string using single or double quotes? Well, the double quote strings are interpreted strings, meaning that any variable name you place in there will be evaluated before the string prints. If you ever need to concatenate string you can use the . operator.

$hello = 'Hello';
echo '$hello world!'; // Outputs $hello world!
echo "$hello world!"; // Outputs Hello world!
echo "$helloish world!"; // Error, $helloish is undefined!
echo "{$hello}ish world!"; // Outputs Helloish world!
echo 'Conc' . 'aten' . 'ate!'; // Outputs Concatenate!

Another thing that might surprise you is that PHP can treat anything as a boolean! Any non-default value will be true while all default values will be false, also called truthy and falsey. The next example uses an if/else statement to illustrate this. Try playing around with it.

if ("Hello") // Try 0, '', '0', 0.1, NULL and array().
{
    echo "Yep...";
}
else
{
    echo "Nope!";
}

So I’ve also shown you an if/else statement. Let’s look at some loops too.

$movies = array('Pulp Fiction', 'Fight Club', 'Star Wars');

for ($i = 0; $i < count($movies); $i++)
{
    echo "$movies[$i] <br>";
}

foreach ($movies as $movie)
{
    echo "$movie <br>";
}

Now there’s actually quite something going on there! First we initialize an array, which we’ve seen before. Now in the first for loop we start by declaring our counter variable $i, then we do a boolean test to check if we need to loop once more and finally we do an update (increment $i) after each iteration. In the boolean check we also use the count(array) function to check if we still have more elements in the array. Ideally you would perform this count outside of the statement so it only gets performed once.
The second loop is a bit more readable. I’m basically saying “for each element, which I will call $movie, in the array $movies do this…”. Now in the loop’s body you can freely use the current element using the $movie variable.
There are also do– and while loops, but I won’t discuss them here. For a programmer this shouldn’t be anything new!

Writing a page

Now let’s write an entire page. Usually you’d have a database, such as MySQL, running, but that’s a bit overkill for this post. So we’re going to read lines of text from a text file and show them on the page. You’ll see that you can update your page without actually modifying your HTML or PHP file.

So let’s first take the example with my favourite movies. We’re going to put our favourite movies in a text file and print them on our page. So create a new PHP file, call it movies.php and put it in the hpdocs folder (which is in your XAMPP folder). Now create a text file called movies.txt and put it in your htdocs folder with your PHP file. You can put some movie names in your text file. Each name goes on a seperate line (I’m calling it movies, but any value would suffice, of course).

For this example I’m going to use an unordered list. I haven’t shown this yet, but the HTML is as follows:

<ul> <!-- Unordered List -->
    <li>Some item</li> <!-- List item -->
    <li>Another item</li>
    <li>Third item</li>
    <li>etc...</li>
</ul>

You could also use an ordered list, in which case you’d use <ol> tags instead of <ul> tags.

So your PHP file could look like this (excluding the !DOCTYPE, html, header and body tags):

<h1>My favourite movies!</h1>
<p>
    <?php
        if (file_exists('movies.txt'))
        {
            echo '<ul>';
            $lines = file('movies.txt');
            foreach ($lines as $line)
            {
                echo "<li>$line</li>";
            }
            echo '</ul>';
        }
        else
        {
            echo 'No favourite movies found!';
        }
    ?>
</p>

So using the PHP function file_exists(string) we’re first checking if the movies.txt file exists at all. If it doesn’t we’ll simply show “No favourite movies found!”, but if it does we’re going to create an unordered list and read the files contents using the file(string) function. The file(string) function reads all lines of a file and puts them in an array. There’s more functions for file manipulation, but I won’t discuss them here. Next we’re looping through the lines we just got from the file. For each line we’re appending a list item element to our HTML. When all the lines are processed we close our unordered list.
And that’s our page! You can view it by navigating to http://localhost/movies.php. You can use some CSS to make it look a bit prettier and you’ll probably want to add some content too.

Now imagine you’d get that out of a database? Pretty neat, huh!

Functions

Now there are times when you have certain code that you want to reuse. Let’s say we want to create another unordered list based on another file. The same rules apply, except maybe we don’t have movies, but songs that we’d like to display. We can create function for this and have the filename passed in as a parameter. So let’s look at how we can put the code above in a function. At the top of your page put the following:

<?php
    function fileAsUnorderedList($fileName, $notFoundMessage)
    {
        if (file_exists($fileName))
        {
            echo "<ul>";
            $lines = file($fileName);
            foreach ($lines as $line)
            {
                 echo "<li>$line</li>";
            }
            echo "</ul>";
        }
        else
        {
            echo $notFoundMessage;
        }
    }
?>

As you can see we’ve defined a function that does the same as our previous code, except the filename and the message when the file is not found are passed in as parameters. Now how can we call this?

<h1>My favourite movies!</h1>
<p>
    <?php
        fileAsUnorderedList('movies.txt', 'No favourite movies found!');
    ?>
</p>
<h1>My favourite music!</h1>
<p>
    <?php
        fileAsUnorderedList('music.txt', 'No favourite music found!');
    ?>
</p>

And look at that! You can now add a second text file to your htdocs folder and your favourite music will be displayed the same as your movies. You still see almost identical code here, so we could change our function and make it do a bit more or we could create a second function that creates the header and paragraph for us.

And what if you wanted to use this function on other pages? Simply put the function in a seperate file and include the following line of code in the PHP file where you want to use the function.

<?php include("MyFunctions.php"); ?>

If you want to further organize your code, and you’ll want that, you’ll have to use objects and namespaces. You’ve already seen a little example of an object earlier and I’m leaving it at that. Be careful with putting functions directly in your files though. What if two files you want to include contain the same functions (or variables)!? You’d have a problem. Using objects and namespaces help toward preventing this.

So that was a very short introduction to PHP. Probably shorter than it deserves. PHP has lots of functions, libraries, third party tooling and a large and active community. If you want to learn more about PHP I suggest you start by Googling for tutorials or perhaps read a book about it. For now you’ve created your first website with dynamic content using a server-side language though! In my next post (which won’t take me another three months) we’ll look at sending data from our website to the server so we can use our page to add movies or music to the text files.

Stay tuned!

Web development #3: Styling our page with CSS 3

This is the third installment of a blog series about web development. You can find other blogs here:

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

In this part of the ongoing series on web development we’re going to apply some style to the web page we created in the previous blog post. So if you haven’t read that one please do, or at least get the page’s HTML at the bottom of that post.

About CSS

CSS stands for Cascading Style Sheet and is used to apply styles to your web page (for example setting backgrounds or changing fonts) and create a layout (position elements relative to each other). CSS, like HTML, has a history of incompatibilities and non-supportive browsers too. While CSS 1 (actually level 1) has been around since 1996 it wasn’t until 2010 that most browsers fully (and more or less correctly) supported CSS. Again, each browser renders web pages differently, making it important to test your CSS in different browsers.

We’re currently at CSS (level) 3. What’s different from CSS 3 compared to it’s predecessors (CSS 1, CSS 2 and CSS 2.1) is that it’s divided into modules like Color, Font and Animations (there’s actually over fifty modules *gasp!*). This allows for various styling options to be developed independently. As a result various modules have various statuses and only a few are actual recommendations (as opposed to draft or work in progress).

Now why is CSS so important? It clearly seperates your content from your visuals. It’s basically what do you want to convey vs. how do you want to convey it. The ‘what’ goes into your HTML and the ‘how’ goes into your CSS. And having seperated this it’s easy to create a new page for your website without having to worry about styling. Or you may want to give your website a cosmetical make-over without having to change it’s contents. As a bonus both your HTML and your CSS documents will look cleaner and be easier to read!

Syntax of CSS

So enough with all those history lessons already! Let’s look at some CSS. There are actually three ways to apply CSS to your HTML. The first is inline, meaning you’re defining it in your HTML elements with a style attribute, which we just said we don’t want to do. The second way is to embed your CSS into your HTML’s head section. That already sounds better than inline, but it’s still not good enough (we’d still have to edit our HTML file for style changes). The third method, and the one we will use, is to define your styling in a seperate file.

So simply start up your text editor (again Notepad or Notepad++) and save it as “mystyle.css” (where “mystyle” is a name of your choosing). The first thing you need to do when applying a style is thinking to what you want to apply the style. Let’s say we want our headers (more specifically our h1 elements) to have a red text color. You’d start by writing a selector. In this case the selector is simply h1. Notice that a comment (for human readers) is started with /* and ended with */.

h1 {
    /* Your style here... */
}

Easy as that. Now inside the curly braces (you know them from C, C++, C#, Java, etc.) we’re going to define the style, which will be applied to our h1 elements. This looks like “property: value;”. So let’s define the red color.

h1 {
 color: red;
}

That’s deceptively easy. Yes, CSS can be that easy, but once your layout gets a bit more complicated… So does your CSS. You can put multiple properties in a single selector too. So save your document (for now preferably in the same folder as your HTML document, or you’ll have to change the path in the href attribute below). We’re going to apply this style to our HTML document (the one from the previous blog). Open up the HTML and add the following line of code to your header (for example at the bottom, just above your </head> closing tag):

<link rel="stylesheet" type="text/css" href="mystyle.css">

I’m not going to elaborate on the link element any further. We’ll see it again when we’re going to use JavaScript. Now open your HTML document and you’ll notice that your header is actually colored red! Pretty awesome.

Selectors

So we just started by writing a selector, in our case the selector for h1. Selectors can be pretty tricky though. Remember that HTML elements can be nested? In our page we have an aside element containing an h2 element and some p(aragraph) elements. Let’s say way want to target that h2 element and make it blue. If we used h2 as our selector all h2 elements would be blue (go on, try it out). We can target elements within elements by combining them in the selector.

aside h2 {
    color: blue;
}

This will make all our h2 elements within aside elements blue. And you can keep combining this. I should mention that any h2 element within the aside element, even when it’s nested into other elements, is now blue. But suppose you only want the h2 elements that are directly parented to the aside element. You can now use a context selector by using the > symbol.

aside > h2 {
    color: blue;
}

Now what if you had two aside elements, both containing a h2 element, and you only wanted one of the two to be blue. For this we have two choices and both requires us to go back to our HTML. The first is working with IDs and the second is working with classes. We’ll look at them both.

Every HTML element can have at least the following two attributes: id and class. We can use them in our CSS (and later JavaScript) to group and/or identify specific elements on our page. In the next example I have modified a piece of our page so it contains some IDs and classes.

<h1 id="title">Our first webpage!</h1>
    <p><abbr class="info" title="HyperText Markup Language">HTML</abbr> stands for <b id="HTMLfull" class="info">HyperText Markup Language</b>.</p>
    <p>The language consists of <i class="info">tags</i> that describe the content of a document.
 For example, a tag can indicate that a certain text belongs to a single paragrah,
 that certain text is more important, less important, that an image should be displayed, or that a new line must be inserted.</p>

As you can see the h1 element has the ID “title” and the b element has ID “HTMLfull”. Furthermore I’ve added the “info” class to the abbr, b and i elements. Now let’s style them in our CSS. Let’s say we want everything that’s “info” to be light blue and we want the text HyperText Markup Language to be bigger too.

.info {
    color: lightblue;
}

#HTMLfull {
    font-size: 150%;
}

Give your IDs and elements a descriptive name, for example “info”, instead of “lightblue”, “lightblue” says something about your style, while “info” says something about your meaning. So in this example I’ve shown you how you can use IDs and classes and even combine them (in case of the b element which is now lightblue and big). Another tip, keep your IDs unique, even though HTML and CSS don’t enforce it.

Now let’s say you want all i elements of class “info” to be purple. No problem!

.info {
    color: lightblue;
}

i.info {
    color: purple;
}

But in this case we have a conflict! The i element should be lightblue, because it has the info class. However, it should also be purple, because it is an i element with the info class. As you can see CSS applies some rules of precedence. As a rule of thumb the most specific selector take precedence over less specific selectors. In this case an i element with class info is more specific than every element with class info, so the i element gets a purple color.

Last, but not least, you can use a * as a wildcard to specify any element. For example, you want every element in an element (let’s say an aside) to have a specific style, but exclude the aside itself. You can use the following.

aside * {
    /* Your style here... */
}

Layout

Now let’s make our page more fancy. Let’s add some layout. First we want our page to only cover a part of the screen, let’s say 50%. We also want to center it in the middle of the screen. That’s a bit tricky, but we’ll have to work with margins (the area around an element). So we’ll define a margin of 0 and let our browser figure it out. We’re also going to put some background picture on our page. I’ve taken a picture from Google and decided to use it as a background (be sure you’re not using any copyrighted stuff!). So we’re going to apply this style to our entire page, which is the body element.

body {
    background-image: url(http://p1.pichost.me/i/24/1475865.jpg);
    width: 50%;
    margin: 0 auto;
}

Wow! Our page is already beginning to look quite nice! Now remember that aside element we had? I want it to stand out a bit. Let’s put a (solid 1 pixel) border around it. I also want it to have a sort of semi-transparent white-y background, if you know what I mean (and if you don’t you’ll see for yourself). Here’s the CSS for our aside element.

aside {
    border: 1px solid black;
    background-color: rgba(255, 255, 255, 0.6);
    padding: 3px;
}

I put the padding there to create some distance between the border and the text. The padding is like the margin we used earlier, but where margin defines the space outside the element padding defines the space inside the element. 3 pixels proved to be enough space (found through a little experimenting).

I’m also still not satisfied with the h2 element within the aside element. I’ve added some extra styling.

aside h2 {
    color: blue;
    border: 2px solid black;
    width: 25%;
}

Blocks

As a finishing touch I want our image to be centered horizontally. Unfortunately that’s not as easy as it sounds. I haven’t mentioned this before, mainly because this is where it matters most, but HTML has two kinds of elements: block elements and inline elements. Basically, block elements represent a significant item that represents a rectangular block of space on a page. Examples of such elements are the p elements, h* elements and ul and ol elements (unordered list and ordered list respectively). Inline elements are smaller items on a page that reside within block elements. Examples are the a, u, em and strong elements.

So far, when we wanted to change the position of an element, they were block elements (the body and h2 elements). The img element, however, is an inline element. That means browsers usually just render them on the same line as their surrounding content and inline position jumps are just a bit weird. So we’ll have to let CSS know to treat the img as a block element before we can reposition it. Luckily that’s pretty easy! We can reposition the image the same way we repositioned the body, using the margin.

img {
    display: block;
    margin: 0 auto;
}

Now look what happens when you alter your paragraph as follows (remember that HTML actually ignores line breaks, so the below example shows the text and image on the same line by default).

<p>HTML 5 is awesome!<br>
Text before the image! 
<img src="http://www.w3.org/html/logo/downloads/HTML5_Logo_128.png" alt="The HTML 5 Logo" title="The HTML 5 Logo">
Text after the image!</p>

Now try turning display: block; on and off (by removing the CSS). See the difference? Also notice that the margin does nothing for the image when it’s not treated as a block element. Now suppose we really need that text on the same line as the image, but we want the image in the center. In this case we can use float to lift up the image and take it out of the normal content flow. You can do this for all block elements and it’s specifically handy to create a menubar on the left or right side of the screen.

img {
    display: block;
    float: right;
    margin-right: 50%;
}

Notice that I float to the right side of the screen and then use the right margin. I do this because if I floated to the left the text would be placed behind the image instead of at the beginning of the line. The float property can also mess up your layout, try using the clear property on adjacent blocks to fix this.

We’ve just seen a small part of CSS. There’s many more properties that you can use to create awesome styles and layouts. Like with HTML CSS is pretty forgiving, meaning that if you made a type your browser will probably figure out what you meant and display your page correctly. Again I advise you to follow the standards and validate your CSS against the W3C CSS Validation Service. Try experimenting with HTML and CSS to get the hang of it and learn new things. Also, don’t miss the next blog!

Stay tuned!

Web development #2: Our first website using HTML

This is the second installment of a blog series about web development. You can find other blogs here:

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

At this point I presume you know a bit about the internet and the world wide web. If you don’t please read my previous blog first. In this part we’re going to take a look at HTML and create our first web page.

The history of HTML

HTML, which stands for HyperText Markup Language, was first presented in 1991 by Sir Tim Berners-Lee, “inventor” of the internet as we know it today and chairman of the World Wide Web Consortium (W3C). HTML was based on SGML (Standard Generalized Markup Language) and was supposed to be the standard language in which web pages would be built. A proper HTML document consists of elements which consist of tags, usually a start and end tag. For example, a header followed by a paragraph in HTML would look as follows:

<h1>This is a header.</h1>
<p>This is a paragraph.</p>

In this example you can see the descriptive (markup) nature of HTML. The tag <h1> indicates “this is where a header starts” and </h1> indicates “this is where a header ends”. The forward slash (/) denotes a closing tag. The entire <h1>This is a header.</h1> makes up an element in HTML. The same goes for the paragraph and the <p> tag.
It is important to note that elements can be nested, but that a nested element must be closed before the outer element is closed. In the following example I will demonstrate this. The identation is purely for readability, it is not actually part of HTML. I’ve also added a little comment. The <!– … –> denotes a comment and is ignored in the HTML, but visible for (human) readers.

<p>
   This is a paragraph.
   <h1>
      This is a header inside a paragraph
   <!--Close h1 before closing p-->
   </h1>
</p>

Whenever a client requests a web page from a web server the web server sends an HTML document. Web browsers, like Internet Explorer, FireFox and Chrome interpret these documents and show you the page (without tags).

In 1995 the HTML 2 standard was released by IETF, introducing new tags and concepts. Subsequent HTML versions (standards) were released by W3C exclusively. HTML 3.2 was released in january 1997 and HTML 4 in december 1997, adding and dropping tags and rules (for both writing and interpreting HTML).

In 2000, after version 4.01, came XHTML (Extensible HTML) which was based on XML rather than SGML. XML is actually a more restrictive subset of SGML and by using XML browsers were able to parse HTML as XML. XHTML was supposed to be a backward compatible XML version of HTML. With XHTML 2 the W3C wanted to make a clean start and break free from the past. Backward compatibility with HTML 4 and XHTML 1 was dropped. Because of the controversy this caused XHTML 2 never saw the light of day as a standard.

In 2008 a first draft version of HTML 5 appeared, building upon XHTML. Almost seven years later (and 14 days ago at the time of this writing) HTML 5 was released as the new standard! Although browsers and developers have been working with HTML 5 for a while now. HTML 5 introduces some new concepts. In this blog post I’m working with HTML 5 and I’m going to explain what makes HTML 5 different while we’re building our first web page.

I recommend you take a look at the HTML 5 standard. It contains a description of all elements and how to use them.

Browser incompatibilities

As said it is up to web browsers to interpret HTML and translate it into visuals on screen. Each browser does this a little differently. As such your HTML code may look different in different browsers. While most browsers nowadays follow the standard pretty well it’s important to check that your website looks okay in different browsers. It’s also one of the reasons you should typically update your browser when updates are available.
Especially Internet Explorer is notorious for being just a little different. Back in the 90’s, when the internet was still young, IE and Netscape were the two browsers you typically used. Of course both wanted to be better than the other. They started making up their own supported HTML tags like <blink> and <marquee> (yes, this was a time when blinking text was considered flashy and high-tech). Netscape disappeared and IE had to support older, non-standard HTML.

Getting started

So enough with those history lessons already! Let’s start creating our very own HTML document. Open up Notepad, type something, save it as “something.html”, open it from the location where you saved it and it will display your text in your default browser. Congrats, you’ve just created your very first web page. That was a bit of an anti-climax, right? While it works, after all you can see your typed text in your browser, creating a well formed HTML document is a bit harder than that (although creating an HTML document is actually that easy). So you can keep using Notepad or use a more sophisticated text editor. I prefer Notepad++, which even has some IntelliSense for HTML. There are other editors too, but I recommend you keep your editor simple while learning.

Now we’re heading somewhere

So, now that you have your editor in place let’s start by creating a real HTML document. First you’ll need to specify the type and version of HTML you’re using (we’ve seen there’s a few). We can do this by using the DOCTYPE tag. The version for HTML 5 has been drastically simplified. The following example illustrates this.

<!--HTML 5-->
<!DOCTYPE html>

<!--XHTML 1.1-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!--HTML 4.01 Strict (not backward compatible)-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

After that we need some <html> tags (starting and ending tags) between which our document will be formed. A document consists of a header, which contains the title and possibly some metadata, and a body, which contains the content of our page. While your page is displayed perfectly fine when you place the header under the body, or when your header does not have a element, it is recommended to place your header above your body and put a title inside your header because that’s the W3C standard.

<!DOCTYPE html>
<html>
    <head>
        <title>Our first web page!</title>
    </head>
    <body>
        
    </body>
</html>

There’s more information you can put in your header, like links to other scripts (CSS, JavaScript…), but we’ll get to that in later blog posts. One thing that is important to mention is the <meta> element. The meta tag has a name attribute and a content attribute. Together they tell something about your page. Let’s look at an example and I think this will be clear. Notice that the <meta> tag has no ending tag.

<head>
    <title>Our first web page!</title>
    <meta charset="utf-8">
    <meta name="description" content="HTML tutorial on sanderrossel.wordpress.com">
    <meta name="keywords" content="HTML,XHTML,HTML 5,Web Development">
    <meta name="author" content="Sander Rossel">
</head>

The body of your document

Now let’s add some body to the document. We have already seen the <h1> and <p> elements. In HTML there are a couple of header tags, <h1> to <h6>. Suppose you have a header for your whole document, this would be h1. But in your document you want to have some additional headers, these would be h2. And any headers inside your h2 would be h3, etc. Again, this is not mandatory, it’s a recommendation. When a page shows more articles (like a blog home page) each article can, of couse, have a h1 header.

<body>
    <h1>Our first webpage!</h1>
        <p>HTML stands for HyperText Markup Language.</p>
        <h2>Important tags</h2>
            <p>Paragraphs are enclosed in &lt;p&gt; tags</p>
</body>

You may be wondering why &lt;p&gt; is looking so weird. Well, imagine that we said “<p>”, and a browser is going to read our HTML, it would think we started a new paragraph! So because the < and > symbols serve a purpose in HTML we can’t use these symbols in ‘regular’ text. Instead we use &lt; for the ‘lesser than’ symbol (<) and &gt; for the ‘greater than’ symbol. We must escape the ampersand symbol (&) and the quote (“) in a likewise manner (&amp; and &quot;).

At this point you may be satisfied with the content, but you may want to style it a bit. Perhaps give the header text another color, use a background, center it in the middle of the screen, etc. This is where HTML 5 is different from its predecessors. In HTML 5 we define no style whatsoever. We use elements only describe the text semantically. For example, we want to make “HyperText Markup Language” bold, because it’s important and we want to italicize “<p> tags” because it’s a technical term. For this we can use the <b>, <strong>, <i> or <em> (for emphasize) tags. Now in earlier versions of HTML the <b> tag meant bold and the <i> tag meant italic, but in HTML 5 they have a different meaning. <b> means we want to draw attention to this text without conveying extra importance. <strong> does convey this extra importance. <i> represents text in an alternative mood, but without emphasizing the importance of the text. <em> is used when you want to emphasize some text.
And that’s the big difference between HTML 5 and everything that came before. In HTML 5 we think of tags in terms of meaning (or semantics). What do we want to convey with this text, without thinking about the visual aspect. In this case I’m going with <b> and <i> because they fit the meaning of the words best (alternatively, I could’ve used <code> for the “<p> tags”).

<body>
    <h1>Our first webpage!</h1>
        <p>HTML stands for <b>HyperText Markup Language<b>.</p>
        <h2>Important tags</h2>
            <p>Paragraphs are enclosed in <i>&lt;p&gt; tags</i></p>
</body>

When you view this body in your browser you’ll probably see some style already. Your <h1> header is pretty large while your <h2> header is a bit smaller. Your <b> element is bold and your <i> element is italicized. This is just some default style, you can easily override it. If the elements fit your meaning, but the way your browser renders them doesn’t (maybe we wanted <b> elements to be red) still go for the elements that convey the right meaning.

There’s plenty of more elements that can help you give meaning to your document. For example there is <article>, <section>, <aside>, <footer>, <small>, <blockquote>, <code>, <abbr> (from abbreviation), <address> (for contact information), etc.

The <a> element represents a hyperlink. It can link to other websites, pages, or a specific place on your current page. The place you want to link to is specified by the href attribute. The text the user has to click on to be redirected comes between the starting and ending <a> tags. Often you’ll find something like: “For my awesome blog click here”, where “here” redirects you to the blog. Don’t be like that, make your linking text descriptive, for example: “You can read more on my awesome blog” where “awesome blog” redirects you to the blog. This is, again a recommendation from the W3C. Here’s a small example of the <a> element (including a target attribute):

<p>You can read all about web development on <a href="http://www.sanderrossel.wordpress.com" target="_blank">my awesome blog</a>!</p>

There’s one last element I wish to discuss, the <img> element. I want to discuss it mostly because we can learn two things from it. First, that we should really use HTML 5 for the meaning of our text, not our styling. And second why we should create our HTML document according to the W3C standards (in a later section).
First let’s look at how we use the <img> tag. Like the <meta> tag the <img> tag has no ending tag. It has one mandatory attribute, the src (source) attribute. Next to the src attribute it is recommended to provide an alt (alternative) attribute, which is used when the image cannot be loaded from the source. It is important that your image is a part of your text (it visualizes or supports your story). DO NOT use <img> to set your background! Again, that would be styling your document and in HTML 5 we are not styling! We’ll see an example in the next section.

Putting it all together

So let’s put all of what we have learned together in a single document. I have created a small HTML file with some elements. I recommend you study the code and read the actual output page.

<!DOCTYPE html>
<html>
    <head>
        <title>Our first web page!</title>
        <meta charset="utf-8">
        <meta name="description" content="HTML tutorial on sanderrossel.wordpress.com">
        <meta name="keywords" content="HTML,XHTML,HTML 5,Web Development">
        <meta name="author" content="Sander Rossel">
    </head>
    <body>
        <article>
            <h1>Our first webpage!</h1>
                <p><abbr title="HyperText Markup Language">HTML</abbr> stands for <b>HyperText Markup Language</b>.</p>
                <p>The language consists of <i>tags</i> that describe the content of a document.
                For example, a tag can indicate that a certain text belongs to a single paragrah,
                that certain text is more important, less important, that an image should be displayed, or that a new line must be inserted.</p>
                <p>A typical piece of HTML may look as follows:<br>
                <code>&lt;p&gt;This is a paragraph with &lt;strong&gt;important text&lt;/strong&gt;&lt;/p&gt;.</code></p>
                <p>Because the &lt; and &gt; symbols are used as part of HTML you'll need to use a special code to display them as plain text.<br>
                You can write them as &amp;lt; (lesser than) and &amp;gt; (greather than).</p>
            <aside>
                <h2>Important tags</h2>
                    <p>Paragraphs are enclosed in <i>&lt;p&gt; tags</i></p>
                    <p>HTML ignores line breaks. Instead we use the <i>&lt;br&gt; tag</i><br>
                    Like this!</p>
                    <p></p>
            </aside>
            <h2>More cool stuff</h2>
            <p>You can read all about web development on <a href="http://www.sanderrossel.wordpress.com" target="_blank">Sander's bits</a>!</p>
            <p>HTML 5 is awesome!<br>
            <img src="http://www.w3.org/html/logo/downloads/HTML5_Logo_128.png" alt="The HTML 5 Logo" title="The HTML 5 Logo"></p>
        </article>
    </body>
</html>

You may want to use more or less elements than I did. Maybe you want to use <section> elements for the different parts, maybe you want more <abbr> elements (by the way, notice the tooltip on <abbr>?). Since HTML 5 is all about semantics (meaning) it’s a bit difficult to tell what is wrong and right. Do we want <strong> or <em>, do we need the <article> element and is it logical to have an <article> element inside an <article> element (or <section> inside a <section>)? It’s mostly up to you!

Why use standards

You might wonder why I’m going through so much trouble to get my HTML right. The <article> element doesn’t change the way my page looks, neither does the <aside> element. Why would I need an alt attribute in my <img> tag if I know the image is available? HTML is pretty forgiving, meaning that if you miss a starting or ending tag your page will probably be correctly displayed anyway.
However, if your HTML page is well formed, meaning your ending tags match your starting tags and all your ‘mandatory’ elements (such as <title> element in your <head> element) and attributes (such as alt attribute in the <img> tag) are in place, the chances that they are correctly displayed in any browser is bigger. In addition your page might load faster.
Search engines can better index your page if your document is well formed, meaning people might sooner find your page.
But what is perhaps most important, and probably something you didn’t think of, is that people with disabilities will have it a little easier to access your page. Someone who is blind cannot see your image, but some software can read the text in your alt attribute to the person. That’s also the reason you should not have “here” link to some page, but rather a description of that page, like “my awesome blog”!

How do you know if your document is well formed? The W3C has a validator that checks various inputs, The W3C Markup Validation Service. I suggest you use it.

We’ve seen a bit of HTML 5, but there’s much more. We might get to that in a later blog. For now we know enough to move on. In the next blog we’re going to add some style to the page we just created using CSS!

Stay tuned!