Tag Archives: HTML

MEAN web development #6: AngularJS in the front

Hi all and welcome back! Welcome back to me too as I’ve been away for a while. Let’s just say I was enjoying a summer vacation from blogging. But I’m back to finish this MEAN series! This week I’ve got AngularJS for you. Maybe next week too.
And in case you need a refresher, here are my previous posts about MEAN:

  1. MEAN web development #1: MEAN, the what and why
  2. MEAN web development #2: Node.js in the back
  3. MEAN web development #3: More Node.js
  4. MEAN web development #4: All aboard the Node.js Express!
  5. MEAN web development #5: Jade and Express
  6. MEAN web development #6: AngularJS in the front
  7. MEAN web development #7: MongoDB and Mongoose
  8. MEAN web development #8: Sockets will rock your socks!
  9. MEAN web development #9: Some last remarks

So in the previous post we’ve seen how we can build pages using the Jade template engine. Pretty sweet, but we need something bigger, better and badder for our front-end.

You can find the examples for this blog on my GitHub page in the mean6-blog repository.

What is AngularJS?

You may have heard of AngularJS before. It’s one of the most popular open-source front-end JavaScript frameworks for the web developed by Google. And, of course, it’s the A in MEAN. But what does it do?

AngularJS is an MVVM framework, much like Knockout.js. It does a bit more than Knockout.js does though. Next to bindings AngularJS can be used for DOM manipulation, more like jQuery. And it does even more, like handling AJAX and routing. As Google likes to put it: AngularJS is “Superheroic” in that it does just about everything.

So instead of talking let’s see some action! First of all we need to install AngularJS. You can download it from the AngularJS website, or you can install it through a package manager such as npm or Bower (install angular). I’ve discussed all three methods in earlier posts so I will not repeat them here. Anyway, if you’ve downloaded my samples from GitHub you’ll be good to go.

The first examples of this post can be tested using nothing but the file system. For later examples with AJAX we’re going to need a little Node.js server, so I’ll add that later. The non-server examples can be found in the front-end.html and the front-end.js files.

So let’s take a look at a first example.

<html>
    <head>
        <meta charset="utf-8">
        <title>AngularJS example</title>
        <script src="node_modules/angular/angular.min.js"></script>
    </head>
    <body ng-app>
        <p>This is your first angular expression: {{ 'This is AngularJS' + ' syntax!' }}</p>
    </body>
</html>

So there are two things going on here. First is the ng-app directive in the body element. This tells AngularJS that body is the root element of our application and that AngularJS should do its magic. You can place it anywhere you want (like in the html element, or maybe a div element somewhere) and a page can have multple ng-app directives (which I won’t be doing in this post).

Next is, of course, the weird {{ }} syntax, which is the syntax AngularJS uses for its bindings. In this case you’ll see that ‘This is AngularJS’ and ‘ syntax!’ are, indeed, appended in your browser, like it was just some JavaScript. Try using {{ 1 + 2 }} and you’ll see it will print ‘3’ since 1 + 2 equals 3 in JavaScript (and not ’12’).

Now let’s look at something really very cool. Suppose you want to bind some value to an input. Here’s how to do it.

<body ng-app>
    <p>Enter you name:
        <input type="text" ng-model="firstName" />
        <input type="text" ng-model="lastName" />
    </p>
    <p>You have entered: {{ firstName + ' ' + lastName }}</p>
</body>

No JavaScript required! Wow, that is so cool! And firstName and lastName are updated real time, while you’re typing! We bound our inputs using the ng-model directive which takes care of creating and binding the firstName and lastName properties.

Enter controllers

You’ll often want more control over your code and putting all of your JavaScript into your HTML is not a good idea. So we’ll want to use AngularJS with some custom JavaScript file that we wrote. This is where things get tricky. Not very tricky, but you just got to know how it works.

An AngularJS application is defined by modules. Modules then define controllers.

angular.module('fullNameApp', [])
    .controller('fullNameController', function ($scope) {
        $scope.firstName = '';
        $scope.lastName = '';
        $scope.fullName = function () {
            return $scope.firstName + ' ' + $scope.lastName;
        };
    });

So as we see here we create a module by calling the angular.module function and passing it more than one parameter. This returns an application so we can call the controller function directly on the return value. In the controller function we pass in the name of the controller, so we can use it in our HTML, and a constructor function, which receives a $scope variable to which we can append properties.

Now our HTML would look like this:

<html>
    <head>
        <meta charset="utf-8">
        <title>AngularJS example</title>
        <script src="node_modules/angular/angular.min.js"></script>
        <script src="front-end.js"></script>
    </head>
    <body ng-app="fullNameApp">
        <div ng-controller="fullNameController">
            <p>Enter you name:
                <input type="text" ng-model="firstName" />
                <input type="text" ng-model="lastName" />
            </p>
            <p>You have entered: {{ fullName() }}</p>
        </div>
    </body>
</html>

So as you can see we’ve now named our ng-app directive and we’ve added a div element with an ng-controller directive which points to our fullNameController controller. Finally, we now use the fullName function. Notice that we could now set default values in our controller and they’ll be displayed on our page automatically.

$scope.firstName = 'Sander';
$scope.lastName = 'Rossel';

More directives

So let’s take a look at some more directives that can help you build amazing pages. ng-repeat can be used to repeat an element for every item in a list. So let’s add a little array on our controller.

$scope.favoriteMovies = [
    'Star Wars',
    'Lord of the Rings',
    'Fight Club'
];

And display it in an unordered list.

<ul>
    <li ng-repeat="movie in favoriteMovies">
        {{ movie }}
    </li>
</ul>

Now we want to be able to add and delete items from the list. This next piece might blow your mind, but there’s a very simple directive to make a text input that can make a comma separated list and convert it to an array real time.

<input type="text" ng-model="favoriteMovies" ng-list />

So we bind the input to our favoriteMovies using ng-model and then use ng-list to convert it to a comma separated list. Try adding “, Pulp Fiction” (or whatever movie you like) to the text input and the movie will automatically be added to the unordered list we had before!
And if you want something else instead of a comma specifiy it in the ng-list, like so:

<input type="text" ng-model="favoriteMovies" ng-list=" | " />

And what if we add objects instead of strings?

$scope.favoriteAlbums = [
    { artist: 'The Beatles', title: "Sgt. Pepper's Lonely Hearts Club Band" },
    { artist: 'Moby', title: 'Play' },
    { artist: 'The Prodigy', title: 'Fat Of The Land' }
];
<ul>
    <li ng-repeat="album in favoriteAlbums">
        {{ album.artist + ' - ' + album.title }}
    </li>
</ul>

So how about making that editable?

<div ng-repeat="album in favoriteAlbums">
    <input type="text" ng-model="album.artist" />
    <input type="text" ng-model="album.title" />
</div>
<button ng-click="favoriteAlbums.push({})">New album</button>

And that’s where we see the ng-click in action. Of course we could’ve called a function on our controller too.

$scope.addAlbum = function () {
    $scope.favoriteAlbums.push({});
};
<button ng-click="addAlbum()">New album</button>

There’s a little problem with ng-repeat that isn’t quite obvious from these examples. ng-repeat creates a separate scope for each object in an array. For objects this is no problem, but if you were binding to an array of primitives, such as integers or strings, the values wouldn’t be updated. So just remember to use objects when wanting to update array elements.

So how about adding a little styling to our page? With the ng-class directive we can add styles to elements based on some boolean value. The best part is you can add multiple classes based on one or more boolean values. So I have added a little embedded CSS to our page.

<style>
    .colored {
        color: red;
    }
 
    .underlined {
        text-decoration: underline;
    }
</style>

And two properties in the controller to specify whether we want some text to be colored and/or underlined.

$scope.addColor = true;
$scope.addUnderline = false;

Now in our HTML we can add two checkboxes for the two properties above and then add an ng-class directive on some element that adds the CSS classes based on the JavaScript properties.

Color: <input type="checkbox" ng-model="addColor" />
Underline: <input type="checkbox" ng-model="addUnderline" />
<p ng-class="{ colored: addColor, underlined: addUnderline }">This text might be colored and/or underlined!</p>

Pretty sweet, right? As you can see ng-class should simply evaluate to an object where each property is a class name with a value true or false to specify whether it should be applied.

But there’s an alternative. We could simply specify a string too. So consider the next JavaScript function which returns a string:

$scope.getClasses = function () {
    var classes = '';
    if ($scope.addColor) {
        classes += 'colored ';
    }
    if ($scope.addUnderline) {
        classes += 'underlined ';
    }
    return classes;
};

We can now use ng-class as follows:

<p ng-class="getClasses()">This text might be colored and/or underlined!</p>

Or you could return an array where each element is either an object such as in the first method or a string such as in the second method. I’ll leave that as practice for the reader though.

Also fun to mention, when you’re inside an ng-repeat directive you can use ng-class-even and ng-class-odd which work exactly as ng-class, but apply the styles only to even or odd elements.

Filters

AngularJS had a feature called filters. It can format values or actually filter lists.

Let’s go back to the first example. Let’s suppose you wanted to show full name in just uppercase or in just lowercase. This is an easy task!

<p>You have entered: {{ fullName() | uppercase }}</p>
<p>You have entered: {{ fullName() | lowercase }}</p>

We can also use a filter to format numbers and dates. It looks kind of the same, except this time you throw in a format.

<p>
    <input type="text" ng-model="number"><br>
    Number (default): {{ number | number }}<br>
    Number (no fractions): {{ number | number: 0 }}<br>
    Number (three fractions): {{ number | number: 2 }}
</p>
<p>
    Date (default): {{ date | date }}<br>
    Date (dd-MM-yyyy): {{ date | date: 'dd-MM-yyyy' }}<br>
    Date (yy/M/d): {{ date | date: 'yy/M/d' }}<br>
    Date (full): {{ date | date: 'fullDate' }}<br>
    Date (long): {{ date | date: 'longDate' }}
</p>

And for arrays you can do some awesome stuff too!  For this we use the orderBy or filter filter.

<h3>Ordered by title</h3>
<ul>
    <li ng-repeat="album in favoriteAlbums | orderBy: 'title'">
        {{ album.artist + ' - ' + album.title }}
    </li>
</ul>
<h3>Ordered by artist reverse</h3>
<ul>
    <li ng-repeat="album in favoriteAlbums | orderBy: 'artist' : true">
        {{ album.artist + ' - ' + album.title }}
    </li>
</ul>
<h3>Filtered on everything with '*y*'</h3>
<ul>
    <li ng-repeat="album in favoriteAlbums | filter: 'y'">
        {{ album.artist + ' - ' + album.title }}
    </li>
</ul>
<h3>Filtered on artist with '*y*'</h3>
<ul>
    <li ng-repeat="album in favoriteAlbums | filter: { artist: 'y' }">
        {{ album.artist + ' - ' + album.title }}
    </li>
</ul>

Keep in mind that we can get these values from our JavaScript controller as well. You can make the most awesome dynamic filters with very little trouble. Just make sure you pass in an object with the same properties as the objects you’re repeating and set their values to the values you’d like to filter.

AJAX with AngularJS

So as mentioned AngularJS does a lot more than just HTML binding. One feature we’re going to look at here is that of the $http service. Needless to say we’ll need a little back-end server to communicate with, so for the AJAX examples I’m going to create a Node.js server and some new HTML and JavaScript so we can serve them up using our Node.js server.

Here’s the server:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var books = [
    { title: 'Lord of the Rings', author: 'J.R.R. Tolkien' },
    { title: 'Harry Potter', author: 'J.K. Rowling' },
    { title: "The Hitchhiker's Guide to the Galaxy", author: 'Douglas Adams' }
];

app.use(bodyParser.json());
app.use(express.static('public'));

app.get(['/', '/index'], function (req, res) {
    res.sendFile(__dirname + '/public/ajax-example.html');
});

app.get('/books', function (req, res) {
    res.send(books);
});

app.post('/addBook', function (req, res) {
    var book = req.body;
    books.push(book);
    res.send(books);
});

var server = app.listen(80, '127.0.0.1');

So there’s a lot going on there. First of all I’ve added some Express. I’m also requiring body-parser (npm install body-parser), which is needed to get our POST data. Then I call the app.use function a couple of times. We’ve seen it before. It simply adds a middleware to a path. In this case we tell it to parse any JSON body so we can use it in our app. We also tell it that we can serve static files from the public folder (so we can serve the HTML and JavaScript file).
After that we serve the page by browsing to the root or root/index. I’ve also specified a GET for root/books, which simply returns a list of books (as JSON). And, what it’s all about, a POST to add a book to the list of books.

Let’s look at our front-end JavaScript.

angular.module('ajaxApp', [])
    .controller('ajaxController', function ($scope, $http) {
        $scope.newAuthor = null;
        $scope.newTitle = null;
        $scope.books = [];
        $scope.getBooks = function () {
            $http.get('http://localhost/books')
            .then(function (response) {
                $scope.books = response.data;
            }, function (response) {
                alert('Something went wrong while getting the books!');
            });
        };
    $scope.addBook = function () {
        $http.post('http://localhost/addBook', { author: $scope.newAuthor, title: $scope.newTitle })
            .then(function (response) {
                $scope.newAuthor = null;
                $scope.newTitle = null;
                $scope.books = response.data;
            }, function (response) {
                alert('Something went wrong while adding a new book!');
            });
        };
    });

So that’s quite a thing too! First of all notice a $http parameter being passed to the controller constructor function. We’ll need this $http parameter to make HTTP calls. Now we first use this in the getBooks function. You’ll see that using this $http stuff is actually very simple! We use $http.get and pass it our URL to get the books. It returns a promise, which has a then function that takes two callbacks, a success function and a failure function. The functions are executed once the asynchronous call returns (AJAX is asynchronous, remember?). So if everything goes right we simply assign the data (a list of books) to the books property. If something goes wrong we show an alert.

In the addBook function I’m using the $http.post function. It’s really similar to the get example, except we’re now passing in some data, a new book. Upon success the book list, including the new book, is returned and we reset the newAuthor and newTitle (nice example of two-way binding by the way).

Now for the HTML:

<html>
    <head>
        <meta charset="utf-8">
        <title>AngularJS AJAX example</title>
        <script src="angular.min.js"></script>
        <script src="ajax-example.js"></script>
    </head>
    <body ng-app="ajaxApp">
        <div ng-controller="ajaxController">
 
            <h2>AJAX example</h2>
            <button ng-click="getBooks()">Get books</button>
            <ul>
                <li ng-repeat="book in books">
                    {{ book.author + ' - ' + book.title }}
                </li>
            </ul>
 
            <input type="text" ng-model="newAuthor" />
            <input type="text" ng-model="newTitle" />
            <button ng-click="addBook()">Add book</button>
        </div>
    </body>
</html>

And there you have it!

So AngularJS can do two-way binding, supports MVVM and MVC architecture, it can do AJAX, but also routing, internationalization and localization, you can write custom directives and customize all you like, it supports testing and it has lots of directives I haven’t discussed like ng-show, ng-hide, ng-form, ng-blur… I guess Google wasn’t exaggerating when they called AngularJS ‘superheroic’ because it really seems to have some super powers!

And of course I’ll be leaving you with some recommended reading. As you know I’m a big fan of the (free) Succinctly series by Syncfusion, so here’s two must reads: AngularJS Succinctly and Node.js Succinctly. Also check out these awesome books by Manning Publications: AngularJS In Action, AngularJS In Depth, Node.js In Action (Second Edition) and Getting MEAN. And a book I’ve recently picked up at work: Pro AngularJS.
Well, that should keep you busy for a few months!

Happy coding!

MEAN web development #5: Jade and Express

In the last few weeks it was my time to shine… In absence. Been quite busy with, you know, stuff. But here I am ready to give you a new installment of the MEAN web development series! If you haven’t read my previous posts, or if you’ve forgotten all about them in my absence, you can find them here:

  1. MEAN web development #1: MEAN, the what and why
  2. MEAN web development #2: Node.js in the back
  3. MEAN web development #3: More Node.js
  4. MEAN web development #4: All aboard the Node.js Express!
  5. MEAN web development #5: Jade and Express
  6. MEAN web development #6: AngularJS in the front
  7. MEAN web development #7: MongoDB and Mongoose
  8. MEAN web development #8: Sockets will rock your socks!
  9. MEAN web development #9: Some last remarks

So in my previous blog from a few weeks back I’ve talked about using Express in Node.js. One thing I haven’t discussed yet is the templating option of Express. As that is actually quite simple this blog will be more about the template engine Jade than about Express. Of course we’ll use both to build a few pages.

You can find the examples for this blog on my GitHub page in the mean5-blog repository.

Starting out with Jade

So you can probably guess our first step (assuming you’ve already installed Node.js)… If it included npm somehow you are correct. We need to install Jade using npm. We’ll also want Express, of course, you know how it goes! You can read about npm and how to use it in my first MEAN article, MEAN web development #1: MEAN, the what and why. So create a folder for your project somewhere, optionally create a package.json file (containing at least an opening and closing bracket), open up a command prompt and use the following commands.

cd C:\project-folder
npm install express --save
npm install jade --save

The –save is optional and only makes sense when you created a package.json file.

Finally create your server.js file where your actual JavaScript goes. So now you have everything you need to start using Node.js, Express and Jade.

Let’s not do that yet though. Let’s take a step back. What exactly is Jade and why would you want to use it? Jade is a template engine, which means you can write some pseudo-HTML which the Jade engine can transform into actual HTML. One reason to use Jade is because it saves typing, “h1 Examples” will output “<h1>Example</h1>” for example. So that saves like seven characters, but it adds up.
Less typing is the least good reason to start using Jade though. When using Jade it is possible to pass some JavaScript object to your Jade code and build your page differently depending on your JavaScript. For example you might have an array and you want to iterate over the array to show a table on your page. Or maybe you just want to show the name of the logged in user in the top right corner.
Jade also supports and encourages a more object oriented style of writing your HTML. That’s awesome because you can now write a piece of HTML Jade once and use it everywhere.

Sounds good, right? But isn’t all of this already possible using PHP, Java or C#? Yeah, sure. And you can even do this in Node.js. Simply create a string containing your HTML, do some string concatenation, replaces, etc. No problem at all.
So why would you still want to use Jade? Because Jade makes it easy! All the string concatenation and replaces you’d have to do in PHP or “vanilla” Node.js is done for you. What’s left is a file that’s easier to read than the HTML it ultimately produces! And the good thing about Jade is that it has Node.js and Express support out-of-the-box!

Hello Jade!

I think that title says it all, no? We won’t be using Node.js and Express just yet though. In fact I want you to fire up a command prompt and install Jade again, this time globally so we can use it from the command prompt.

npm install jade -g

Now create a folder in the Node.js project we just created and call it jade-examples. We’re going to use this folder and some of the examples later with Node.js and Express. So in that folder create a file and call it hello-jade.jade. If you got my sources from GitHub you can find the file in jade-examples. Put the following code in the file.

html
  head
    title Hello, Jade!
  body
    h1 Hello, Jade!
    p This is awesome!

So that’s maybe a bit much for a simple Hello World example, but I’m pretty sure you can figure out what HTML this will generate. One thing I’d like to point out is that Jade is whitespace sensitive. More specifically, you must use whitespaces to nest elements. That means that you got to be really careful with your spaces, they’re not just makeup!
I recently spent an evening debugging some Haskell code (which is also whitespace sensitive) because I had used spaces on one line and a tab on another. Try figuring that out, it all looks the same!
I recommend using spaces by the way, if your editor supports it look for the option that converts tabs to spaces and you’ll be safe.

So how to get some HTML out of this? With the command prompt, of course. So browse to the folder where you’ve put your file and use the following command.

cd file-folder
jade hello-jade.jade

Now check it out, it generated a hello-jade.html file. It’s not very readable though. Everything is put on a single line! Let’s fix that. You can use some options in the command prompt. We’re going to use -P (that’s a capital P).

jade hello-jade.jade -P

Looks a look better, doesn’t it?

<html>
  <head>
    <title>Hello, Jade!</title>
  </head>
  <body>
    <h1>Hello, Jade!</h1>
    <p>This is awesome!</p>
  </body>
</html>

For multiline text you should use one of the following methods. Use a dot after your element or use pipes | on every single line.

p.
  This is one line.
  This is a second.
p
  |This is one line.
  |This is a second.
p
  This won't work.
  It just won't.

The HTML that is generated looks as follows.

<p>
  This is one line.
  This is a second.
</p>
<p>
  This is one line.
  This is a second.
</p>
<p>
  <This>won't work.</This>
  <It>just won't.</It>
</p>

As you can see Jade will happily generate syntactically correct, yet invalid HTML! Keep in mind that HTML isn’t whitespace sensitive so the above HTML will still render the two lines of text on a single line in your browser. If you need a seperate line you’ll have to insert a <br> element.

Doing more with Jade

So now that we’ve got that out of the way let’s look at some other features of Jade. Of course you can add attributes to your elements.

h1(id="header") Attributes
p(class="text") This is an example using attributes.
p Here's a text input.
input(type="text")

I won’t show you the HTML output as you can generate it yourself or look at the files from my GitHub.

Here’s some other stuff we can do with Jade.

// This comment will be visible in our HTML.
//- This one won't (it's the hyphen!)
//- Ids are so common we have a shorthand!
h1#header Attributes
//- Same goes for classes.
p.text This is an example using attributes.
p.text.second-class.third-class Here's a text input.
input(type="text")
//
  Block comment
  With lots of space
  And lines

p Some text with another <strong>element</strong>.

//-
  Yes, this is possible,
  but we need to put it on a new line
  and prefix it with a pipe.
| Some text without enclosing tags.

Using JavaScript

So that’s all pretty cool, but you probably want more. You’re in luck, because there’s much more! In fact, you can use JavaScript to generate HTML. That means you can have any JavaScript object and use it just like that.

For the next example we’re going to need two files. First is our Jade file. I’ve called it javascript.jade.

h1= title
p= text

The = sign means some code will follow. So “title” and “text” is actually code. More precise they’re properties/variables. Using = will also filter your JavaScript to prevent injection attacks. If you like to disable this feature simply use != instead.

You could generate HTML from the above Jade file, but since title and text are not set you’ll just get an empty header and paragraph. So we’ll need to pass in something to the engine so it knows how to interpret those values. We can do that using a JSON file. So create another file, I’ve called it javascript.json, and put in the following JSON.

{
  "title": "Jade and JavaScript!",
  "text": "You can just insert JavaScript Objects into your templates!"
}

Now we can use the command prompt to generate the HTML using the JSON file. Notice that we’ll use a capital O in the next sample.

jade -O javascript.json javascript.jade

This will generate the HTML and it will have replaced title and text with the values from your JSON file. Awesome!

In the next example I’ve included all JavaScript into the Jade file so we don’t need a seperate JSON file. Try setting the showHeader variable to false and generate the HTML again. Also notice the difference between the escaped and the unescaped code.

//-
  The following code
  will not be shown
  in your HTML.
  We'll use - instead of =

-
  var showHeader = true;
  var header = 'Jade is awesome!'

//- Single line code.
- if (showHeader)
  h1= header

//- Native Jade syntax!
if showHeader
  h1= header

//- Multiline code.
-
  var movies = [];
  movies.push('Star Wars');
  movies.push('Lord of the Rings');
  movies.push('Harry Potter');

ol
  each movie in movies
    li= movie

- var code = 'HTML may look like this: <p>Hello, Jade!</p>';
//- Some escaped code.
p= code
//- Some unescaped code.
p!= code

Inheritance

So how about we look into that inheritance now? Most, if not all, websites have a standard structure that’s the same across the entire page. We have a header at the top, footer at the bottom, a menu on the left, top or right and the content in the middle. And it’s usually the middle part that changes while the rest stays more or less the same. So let’s define that basic layout. I’m going to keep it simple so I’ll just have a page with a fixed footer. For simplicity I’m just going to use embedded CSS in our Jade template. I’ve called the following file base.jade.

html
  head
    style(type="text/css").
      html {
        position: relative;
        min-height: 100%;
      }

      body {
        margin: 0 0 100px;
      }
 
      footer {
        background-color: #41a62a;
        position: absolute;
        left: 0;
        bottom: 0;
        height: 100px;
        width: 100%;
      }
    block head
  body
    div#content
      p This is the content!
      block content
    footer
      p This is the footer!
      block footer

This looks a lot like what we already know. The only weird thing here are those blocks. The block elements aren’t visible in the generated HTML, so it’s completely possible to use a ‘base’ page as a regular page on your site.
Now those blocks can be overridden by inheritors. So block content can be replaced with anything you like. Let’s see what that looks like. I’ve created an base-inheritor.jade file which extends base.jade.

extends base.jade

block head
  title Inheritor

block content
  p This is the inheritor page!

block footer
  a(href="#") Some link

The file starts with extending base.jade (that’s actually the relative path to the file, since I have it in the same folder it’s just the file name). After that I’m filling in the content for each block. It’s totally optional to override a block.
Now you can simply generate the HTML for base-inheritor.jade and you’ll see the entire base is generated too!

There’s a little more you can do with those blocks though. Here’s a simple file called blocks.jade.

block header
 h1 Inheritance using Jade!

block content
 p Here is some content.

block footer
 p This is the footer.

As you can see I’ve put some content in each of those blocks. In an inheritor we can replace that content, append to that content or prepend to that content. This is illustrated in blocks-inheritor.jade.

extends blocks.jade

block header
  h1 Another header!

prepend content
  p This is even more content!

append footer
  a(href="#") Some link

You may use “block append” or “block prepend”, but the block keyword is optional. Now generate the HTML and check out the results!

It’s also possible to put blocks in blocks, but I’ll leave that as practice for the reader.

Mixins

Now there is one last feature I’d like to show you, which is mixins. A mixin is a bit like a function, a reusable piece of Jade! Let’s just look at some examples.

//- Here is a mixin.
mixin lorem
  h2 First paragraph of Lorem Ipsum...
  p Lorem ipsum [...]

h1 Mixins
//- Mixin usage is a big plus!
+lorem
+lorem
+lorem

h2 Animals
- var animals = ['Cat', 'Dog', 'Goldfish'];

//- A mixin with a parameter and JavaScript!
mixin isKnownAnimal(animal)
  if animals.indexOf(animal) >= 0
    p= 'The ' + animal + ' is a known animal.'
  else
    p= 'The ' + animal + ' is not a known animal!'

+isKnownAnimal('Cat')
+isKnownAnimal('Dog')
+isKnownAnimal('Parrot')

Pretty awesome, right?

Express

So that’s all the Jade I’ve got for you! You can now create Jade pages and generate HTML through the command prompt. We’d use it within Node.js though! So the time has come to get back to the project we created at the start of this post.

In the server.js you need to do two things. Tell Express where to find its templates and what engine to use when rendering those templates. Then on a request render any template you like.
It’s that easy!

Now we’ve got all these Jade examples we can generate using Express! I picked a few interesting ones. Here’s the code for the entire server.js.

var express = require('express');
var app = express();

app.set('views', './jade-examples')
app.set('view engine', 'jade');

// Use hello-jade as index.
app.get('/', function (req, res) {
    res.render('hello-jade');
});

app.get('/javascript', function (req, res) {
    res.render('javascript', {
        title: 'Jade and JavaScript!',
        text: 'You can just insert JavaScript Objects into your templates!'
    });
});

app.get('/base-inheritor', function (req, res) {
    res.render('base-inheritor');
});

app.get('/mixins', function (req, res) {
    res.render('mixins');
});

var server = app.listen(80, '127.0.0.1');

Is that all? That’s all!

So I usually give you some reading recommendations at the end of a blog, but I really haven’t got anything for Jade. You can get a lot from the language reference on the Jade website, although it’s hardly a good place to start.
Of course you can always check out some books by Manning, like Express.js in Action, which has a chapter on templating in Express and Jade. And keep an eye out for the ebooks by Syncfusion. Node.js Succinctly has a chapter on Express and JavaScript Succinctly is always handy when working with JavaScript.

Hope to see you again next week.
Stay tuned!

Polymer for reusable web components

Wait, what? No MEAN Web Development #4? If you’ve been following my blog you’ll know I’m in the middle of a series on MEAN Web Development. Don’t worry, I’ll get back on that!

The thing is I went to an event by CoolBlue, a Dutch webshop, last week and they had a talk on their own CDN and on Polymer 0.5. While the CoolBlue CDN is quite interesting it isn’t a very good topic to blog about. Polymer looked pretty cool too though, so I wanted to blog about that while it’s still sort of fresh in my memory. Of course I won’t be writing down exactly what was told at the CoolBlue presentation. Instead I’m going to hook in on it. You probably weren’t there so let me give you a quick recap.

“Polymer 0.5, the version CoolBlue used, is great if you’re using Chrome. Polymer 0.8 (which is still in alpha) will make lots of breaking changes to the API, but it contains the proposed API for version 1.0 and fixes some shortcomings, like performance, from 0.5.”

So if anything Polymer isn’t quite production ready. I’ve never been much of an early adopter, but today that’s going to change. In this blog I’ll be discussing Polymer 0.9 (the plan was 0.8, but then 0.9 came out while I was writing)!

You can find the source code of the examples on my GitHub account in the polymer-blog repository. You’ll need to run them from a web server (I’ll explain how to do that in this post).

Also be sure to follow me on Twitter @sanderrossel for news and articles on (web) development.

Web components

But what exactly is Polymer? Polymer is a library for creating web components developed by Google. But what is a web component? Actually there’s an entire website dedicated to teaching you about web components, WebComponents.org. Let me give you a quick summary.
Web components allow you to create custom HTML elements that contain other HTML, CSS and JavaScript. That way you can, theoretically, build websites by composing HTML, rather than nest HTML, call some JavaScript, add some CSS, throw it in the mixer, and get a mess.
So by encapsulating HTML, CSS and JavaScript we can create custom HTML that we can (re)use to compose new components or pages.

An important part of web components is the Shadow DOM (sounds like something from a video game, right?). Anyway, the shadow DOM is like ‘invisible’ HTML in your HTML document, a DOM that exists next to your DOM. Think of it as a sub-DOM, but that you can’t see. So far only Chrome and Opera support the shadow DOM.

For that reason web components are currently mostly implemented using polyfills, a downloadable piece of code that fakes native support by adding modern HTML and CSS functionality to older browsers as if they were part of the standard API.

As you can see web components still has a long way to go before it’ll be supported natively by browsers and reach maturity, but luckily nothing is stopping us from already taking a look at it today. And if nothing of that rang any bells, don’t worry, it’ll become clear once we look at some examples!

Bower

First things first. We need to get Polymer up and running in our project. We have a couple of ways to do this. First, and this is the recommended way, we can install Polymer by using Bower, a package manager for the web. Alternatively we can download some zip file containing all necessary files and use that. Lastly we can pull Polymer directly from GitHub and get all the related software manually.

So let’s go with Bower. I’m assuming you’re not familiar with Bower yet (neither am I), so I’ll walk you through it step by step (assuming you’re on a Windows system). If you already know Bower, or you’d like to install Polymer using one of the other proposed methods, feel free to skip this part. I won’t be discussing the other methods.

First we need to install Bower. Even though Bower is a package manager we need a package manager to install it. More specifically we need npm (and also Node.js). You can get both on the Node.js website. Luck has it that I already discussed how to install Node.js and npm in a previous blog, MEAN web development #1: MEAN, the what and why. So I suggest you read it, or at least the part on installing Node.js and Express (that last part shows you how to use npm).

Once you’ve got Node.js and npm installed you’ll need Git. No doubt you’ve heard about Git. It’s the source control system developed by mr. Linux, Linus Torvalds, himself. You can get Git from their downloads page. When installing be sure to check the box that says “Use Git from the Windows Command Prompt”! Other than that you can leave all the defaults in place.
If you use GitHub and already have the GitHub software installed you’ll still need to install Git. GitHub is a client for the GitHub website and though it does use Git, it doesn’t use it on your local machine.

Now that we have all we need to use Bower we can actually install Bower! Open up a command prompt (yes, Bower uses the command prompt too…) and install it using npm.

npm install bower -g

Now installing Polymer is a breeze. Create a folder where you’d like to have your project, navigate to it using your command prompt and install Polymer like you would do when using npm (their syntax is very much the same).

cd "C:\MyProjects\PolymerProject\"
bower install Polymer/polymer#^0.9.0

Alternatively you could create a bower.json file, much like the Node.js package.json, and keep track of your installed packages. You can create a bower.json file manually or use the command prompt and walk through some sort of setup. In the command prompt use the following command (still in your project folder).

bower init

If you want to leave a field blank just press enter. Now you can install packages using –save and the bower.json will be updated automatically.

bower install Polymer/polymer#^0.9.0 --save

You can also omit the version and just get the latest.

After installing Polymer my bower.json looked like this.

{
    "name": "polymer-blog",
    "version": "1.0.0",
    "authors": [
        "Sander Rossel"
    ],
    "main": "index.html",
    "homepage": "http://sanderrossel.com",
    "ignore": [
        "**/.*",
        "node_modules",
        "bower_components",
        "test",
        "tests"
    ],
    "dependencies": {
        "polymer": "Polymer/polymer#~0.9.0"
    }
}

Yours may look differently dependent on what you entered in the setup.

There’s a lot more you can do with Bower, but I’ll leave it at this as this blog is actually about Polymer!

Polymer

And then we’re finally getting to Polymer! Unfortunately, because of some browser security issues, we’re going to need to run our HTML, CSS and JavaScript examples on an actual web server. No problem of course, since I already blogged about that too. So read the part “Setting up your environment” from Web development #4: PHP in the back and once you’ve installed XAMPP we’re ready to go. I’d like to make a small addition to the paragraph from that post. The default port 80 was in use on my computer (it happens). If you have the same problem either shut down the program that is using port 80 or change the port in XAMPP by going to Config -> Service and Port Settings -> Apache and change the main port.

Because we need a server I’ve put all of the examples on the same index.html page. As I already mentioned, the shadow DOM is pretty important when creating Polymer web components. By default Polymer puts the HTML tree in the main DOM though, so we’ll want to turn this off and put it in the shadow DOM instead (so the Polymer components are really self-contained). As far as I understand putting the components HTML in the shadow DOM will be default when Polymer 1.0 is officially released, for now I’m putting the following script in my header though.

<script>
    window.Polymer = window.Polymer || {};
    window.Polymer.dom = 'shadow';
</script>

On to the example. First you’ll need to install Polymer in your htdocs folder. After that create another folder called “components”. In components create a file called “hello-polymer.html”. In that file put the following HTML.

<dom-module id="hello-polymer">
    <template>
        <h2>Hello, Polymer!</h2>
        <p>This is our Hello World example.</p>
    </template>
</dom-module>
<script>
    Polymer({is: "hello-polymer"});
</script>

Now in your htdocs folder create an index.html file and put the following HTML in it.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Hello, Polymer!</title>
        <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
        <link rel="import" href="bower_components/polymer/polymer.html">
        <link rel="import" href="components/hello-polymer.html">
    </head>
    <body>
        <hello-polymer></hello-polymer>
    </body>
</html>

So let’s first look at the hello-polymer.html file. We start off by opening a dom-module element. Note that this is not an HTML standard! We can recognize non-standard elements by the hyphen (- symbol) in the name. For that reason, the value of our id attribute must contain at least one hyphen. The id indicates the name of  our custom element. So I’ve called it hello-polymer.
Within the dom-module element we’ll find a template element. That’s where our HTML goes. I’ve simply put an h2 header and a little paragraph in it. So that’s two elements.
Last, but not least, we need to register our custom element. We can do this by calling the Polymer function and passing it an object with the is-property and setting it to the name of our custom element.
So that’s it!

Now how can we use this custom element we just made? In the index.html you’ll need some imports. First you’ll need webcomponents-lite.min.js, second you’ll need polymer.html and last you’ll need our custom element. It’s actually these link elements that require us to use a server, as Chrome is pretty strict with linking HTML on your page.
So now we can just use our custom element! <hello-polymer></hello-polymer> is all it takes. Try it out by browsing to localhost.
Even though our body contains just one element, we can see two! Awesome!

So let’s make that a little bit more exciting. Create another file in the components folder, I’ve called it “expandable-hello-polymer.html”, and put the following code in it.

<dom-module id="expandable-hello-polymer">
    <style>
        .invisible {
            display: none;
        }
    </style>
    <template>
        <button id="btn">Click me!</button>
        <div id="body">
            <h2>Hello, Polymer!</h2>
            <p>This is our expandable Hello World example.</p>
        </div>
    </template>
</dom-module>
<script>
    Polymer({
        is: "expandable-hello-polymer",
        ready: function() {
            var btn = document.getElementById('btn');
            btn.onclick = function() {
                var body = document.getElementById('body');
                body.classList.toggle('invisible');
            };
        }
    });
</script>

In this example I’ve added a little CSS in the style element. The template contains a little more HTML too. The real trick lies in the script though. I’ve defined the ready function on the object passed to the Polymer function. Ready is executed, well, when the element is ready. The JavaScript itself is not very exciting, so I won’t get in on that.

Now what if we did the following in the example above?

<div id="body">
    <hello-polymer></hello-polymer>
</div>

That would’ve worked too! We can just use custom elements in our custom elements. We need to make sure the custom element we want to use is loaded though, we can load them in the current file (I’d recommend that) or in the file where we load our custom elements.

There’s still a little problem with the JavaScript in the above example. What if we have more elements with the id “btn”? After all, our document using the custom element doesn’t know about the button, so it might have another button with the same id. Which button will the above code fetch, the local one or the other one we don’t know about yet? This is especially tricky when not using the shadow DOM. We don’t know so let’s fix this problem. We can actually use the this object in the ready function to get access to the local DOM only. Notice that I’ve aliased this to that, since this won’t be this in the onclick event (hooray for JavaScript…).

ready: function() {
    var that = this;
    var btn = that.$.btn;
    btn.onclick = function() {
        var body = that.$.body;
        body.classList.toggle('invisible');
    };
}

So we can use this.$.elementId to get any element.  Alternatively we could use this.$$(selector) to get dynamically injected elements. $$ only returns the first found element.

And of course we can use it as follows.

<expandable-hello-polymer></expandable-hello-polymer>

In the example above you’ll notice that the text in the paragraph is now equal to the text in the hello-polymer example and we can’t change that. So what if we did want to change values inside our custom web component from the outside? The next example shows how we can use binding and how we can change attributes from outside of the Polymer component.

<dom-module id="attributes-polymer">
    <template>
        <span>This is <span>{{firstname}}</span> <span>{{lastname}}</span>'s custom element!</span>
    </template>
</dom-module>

<script>
    Polymer({
        is: "attributes-polymer",
        properties: {
            firstname: "",
            lastname: ""
        }
    });
</script>

So here we see that Polymer supports binding. If you’re familiar with AngularJS you’ll recognize the syntax. You can see we pass an object to the properties in the Polymer function. In these properties we specify the attributes we can use within this Polymer component, so firstname and lastname (attributes can’t have capitals). Then with the {{attribute}} syntax we can (two-way) bind to them. There’s an alternative syntax, [[attribute]], that indicates one-way binding. Binding is not possible with string concatenation, so I’ve put the bindings in their own span elements, that way we don’t need to concatenate.
Now in the index.html we can have the following.

<!DOCTYPE html>
<html>
    <head>
        <!-- ... -->
    </head>
    <body>
        <div>
            <label for="firstNameInput">Whose element is this?</label>
            <input id="firstNameInput" type="text" />
            <input id="lastNameInput" type="text" />
 <button id="btn">Change name</button>
        </div>
        <attributes-polymer id="elem" firstname="Sander" lastname="Rossel"></attributes-polymer>
    </body>
</html>

<script>
    var btn = document.getElementById('btn');
    btn.onclick = function() {
        var firstName = document.getElementById('firstNameInput').value;
        var lastName = document.getElementById('lastNameInput').value;
        var elem = document.getElementById('elem');
        elem.firstname = firstName;
        elem.lastname = lastName;
    };
</script>

And as you can see the values of firstname and lastname change value when you press the button.

There’s one last example I want to look into, two-way binding. This is a powerful feature that is actually pretty easy to use! So let’s put the example above in a Polymer web component and apply two-way binding to it. That means we don’t have to press a button to update the firstname and lastname values!

<dom-module id="two-way-binding-polymer">
    <template>
        <h2>Two-way binding!</h2>
        <div>
           <label for="firstNameInput">Whose element is this?</label>
           <input id="firstNameInput" type="text" value="{{firstname::input}}" />
           <input type="text" value="{{lastname::input}}" />
        </div>
        <span>This is <span>{{firstname}}</span> <span>{{lastname}}</span>'s custom element!</span>
    </template>
</dom-module>

<script>
    Polymer({
        is: "two-way-binding-polymer",
        properties: {
            firstname: {
                type: String,
                notify: true,
                value: "Sander" // optional
            },
            lastname: {
                type: String,
                notify: true,
                value: "Rossel" // optional
            }
        }
    });
</script>

There are a few things to notice here. First is the firstname and lastname properties. They’re now objects rather than just empty strings. To use two-way binding we need to set the notify flag. We also need to set readOnly to false, but since that’s a default I haven’t set it explicitly (but now you know there’s such a thing as readOnly too). Also, we must use {{attribute}} syntax for two-way binding. Last, the elements we’re binding to need to have a property-changed event. Since we’re binding to a non-custom element that doesn’t have a property-changed event we can specify the event on which to react ourselves. We do this by using the “property::event” syntax, in this case “firstname::input” and “lastname::input”.
The usage of this element is again very simple.

<two-way-binding-polymer></two-way-binding-polymer>

Conclusion

There’s obviously a lot more to Polymer and web components than what I’ve discussed in this post. At least you’ve got a little look at web components and Polymer in particular.
Now should you use this? As I’ve said before Polymer is still under development. In fact, when I wrote this article a new version came out which had some breaking changes! Next to that Polymer won’t work well (or different) on other browsers. Hopefully that’ll be fixed in different versions (of either Polymer or those other browsers).
That said, web components are awesome and really allow for some modular front-end development! Web components are also something the W3C is looking into standardizing. So I’d be looking out for Polymer, but wait until at least version 1.0 before even considering taking this into production code.

Happy coding!

MEAN web development #2: Node.js in the back

A series on MEAN and the first actual article in which we’ll get some web pages served starts with the N, the very last letter of MEAN! Yes, it’s true, we’re starting in the back, literally and figuratively speaking. Node.js will be your server side software and you’ll use it to handle incoming HTTP requests. Once we’ve got this going we’ll be able to get to the other letters of MEAN (MongoDB, Express and AngularJS in case you forgot). And in fact we’ll already be looking at some of that E, for Express, in this post!

For a change I won’t mention you should follow me on Twitter because that’s where I tweet on anything software, MEAN and Node.js related and I won’t mention my Twitter handle is @sanderrossel either.
So now that I haven’t mentioned that I am going to mention my GitHub account because that’s where you’ll find the source code for this blog post. You can find the repository for this post in the SanderRossel/mean2-blog repository.

By the way, if you’re just dropping in and you haven’t read the first post in this series yet you really should.

  1. MEAN web development #1: MEAN, the what and why
  2. MEAN web development #2: Node.js in the back
  3. MEAN web development #3: More Node.js
  4. MEAN web development #4: All aboard the Node.js Express!
  5. MEAN web development #5: Jade and Express
  6. MEAN web development #6: AngularJS in the front
  7. MEAN web development #7: MongoDB and Mongoose
  8. MEAN web development #8: Sockets will rock your socks!
  9. MEAN web development #9: Some last remarks

Getting started

Maybe the title of this post seems familiar? I’ve written on a back-end technology before, Web development #4: PHP in the back. In that blog post I explain how to write PHP and how to get it working on your own machine by installing some web server software, XAMPP. Here’s the cool thing about Node.js. It is a web server already, so you don’t need to install anything besides Node.js (which we did in the first part of this series). You can just write JavaScript and run your server!

So let’s look at the “Hello world” example from the first article again.

var http = require('http');
var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, Node.js!');
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

I’ve written it a bit different from my first post, so we can see what’s going on just a little bit better. There are a few things going on there. First of all is the ‘require‘ bit. With require we can load a module which we can use to implement certain functionality. So what’s a module? Node.js has a pretty cool module system, where a module can be compared to classes like we have in C# or Java. We’ll look at modules in more detail in a next post. So anyway, with the first line of code we’re telling Node.js that we need the http module and we store it in the http variable.

So now that we have this http module, or class-like thing, we can invoke functions on it. And the first (and only) function we’re going to call is createServer. So createServer takes an (optional) callback function as parameter. The callback function takes a request and a response as input parameters which we can use to see what the user requested and to return anything back to the client.
As you can see we’re writing to the header of the response, using writeHead, to tell it that everything was handled correctly (HTTP code 200 is OK) and that we’re sending back some plain text. By calling response.end we’re telling Node.js we’re done and that the result is ready. Response.end must be called on each request (or our client will be waiting on a response forever) and it must be called as the final operation on our response object, since it signals that the response is complete (all headers and content have been written to the response). In this case we’re passing our response text directly to the end function, but alternatively we could use the write function and simply call end without parameters. That would look as follows.

res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello, Node.js!');
res.end();

Or, if you want to build up some response text, you can do something as follows (using write n times).

res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello,');
res.write(' Node.js!');
res.end(' [This text is optional]');

And, of course, we’ll typically return HTML rather than plain text. Notice I’ve changed the header too.

res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello, Node.js!</h1><p>This is a paragraph...</p>');

So now that we’ve called the createServer function and we’ve specified what to return we have a Server object. This Server object has functionality to listen for incoming HTTP requests and handle them accordingly. To start listening simply call the listen function and pass it a port and an IP address. I’m still using 1337 and localhost from the Node.js website example.

Last, and actually also least, is the console.log, which just logs some debug info to your command window when starting your Node.js app.

You can run each example by opening up a command prompt and typing in (exluding double quotes (“”)) “node pathToMyFile\MyFile.js”. If your file path contains any spaces be sure to wrap it in double quotes.

Debugging

Did you try out all those examples? Did you have to restart the command prompt and type in “node pathToMyFile\MyFile.js” a couple of times? Tiresome, isn’t it? Luckily there are tools that automatically restart your Node.js app when changing a file. You really should install one and save yourself time and trouble! I’m going to use nodemon. You can install it using npm. Open up a command window and type “npm install nodemon -g”. The -g tells npm to install nodemon globally. That means nodemon isn’t some library that this one project uses, it’s a global library from which all your projects can benefit! Whoohoo, never again restart your Node.js app manually because you’ve made a minor file change! To make sure nodemon installed correctly open up a command prompt and type in “nodemon -v” and you should get the currently installed version of nodemon.
Now instead of starting your Node.js app using “node pathToMyFile\MyFile.js” use “nodemon pathToMyFile\MyFile.js” (simply replace node with nodemon). Now go ahead and edit your file. Watch the command prompt and see how your app is automatically restarted. Browse to your website (localhost:1337) and see that the Node.js app has indeed restarted.

For some more tips on debugging web apps in general (no matter if you’re using Node.js, C# ASP.NET, Java or what have you) you should read a previous blog post I wrote, which has a little section on debugging web pages from your browser, Web development #8: Where to go from here.

Doing a little more

So here’s a nice one for you.

res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Requested: ' + req.method + ' - ' + req.url);

Try putting that in the createServer callback. Now browse to localhost:1337/SomePage or localhost:1337/AnotherPage?someParam=someValue. You should see whatever you put after localhost:1337 echoed in your browser window.

So let’s say we have some HTML pages that we want to show based on the requested page. This is now pretty easy. Here’s a first, and rather naive, implementation. In case you got my source from GitHub, the final implementation can be found in the file nope.js (that kind of gives away the ending, doesn’t it?).

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
    switch (req.url) {
        case '/about.html':
            res.writeHead(200, {'Content-Type': 'text/html'});
            var buffer = fs.readFileSync(__dirname + '\\about.html');
            res.end(buffer.toString());
            break;
        case '/index.html':
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            var buffer = fs.readFileSync(__dirname + '\\index.html');
            res.end(buffer.toString());
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.end('<h1>404 - Page not found!</h1><p>What were you even trying to do...?</p>');
            break;
    }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

So there’s some new stuff in there. First we require(‘fs’), which gives us some control over the file system (fs is short for File System). After that we do a switch statement on the request url. We support no url (just localhost/1337, we’ll get url “/”), /index.html and about.html. Everything else will get a 404, page not found. Note that no url and index.html both give you the index.html page. So make sure you have an index.html and an about.html page in the same folder as your Node.js app. If you got this from my GitHub account you’ll be fine, otherwise you’ll need to create those files and put some HTML in them.
So if you browse to localhost:1337/index.html or about.html we’ll first set the header to 200 and text/html. After that we’ll use the fs object to read either the index.html or the about.html file.
Notice that I’m using readFileSync. Remember that I explained, in my first post in the series, that Node.js runs a single thread to handle all incoming requests? Because any synchronous action (meaning it just runs on the same thread) is blocking that one thread everything in Node.js is asynchronous by default. So any non-asynchronous (synchronous) method is suffixed with ‘Sync’. If, like me, you’re coming from C# that’s just the other way around from what you’re used to!
So anyway, we read the file and we now get some buffer object. To get the actual contents as a string simply call the toString function on the buffer.
We also see the __dirName variable, which is a global Node.js variable which contains the directory in which your Node.js JavaScript file resides.

There is an overload for the readFileSync that will return the string value instead of the Buffer object.

var content = fs.readFileSync(__dirname + '\\index.html', 'utf8');
res.end(content);

So there are a few problems with this code. First of all we are reading files synchronously. Suppose this takes 50 milliseconds. No big deal you’d say, but suppose you have 100 requests per second, that’s 5000 milliseconds, or 5 seconds, for the 100th visitor! Imagine that every 100th visitor had to wait 5 seconds, at least, for your page to load. That’s rather disastrous for a web page! So we really want to read that file asynchronous. Luckily that’s pretty easy. We can use the readFile function which takes a callback function as last parameter. The callback function gets an error object and the returned data as input parameters. So how would that look?

fs.readFile(__dirname + '\\index.html', 'utf8',
    function (err, data) {
        if (err) {
            // Handle exception...
        } else {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        }
});

Second, we’d best put the file handling in a seperate function. We now have this ‘huge’ piece of duplicated code! So let’s tidy it up a bit.

var http = require('http');
var fs = require('fs');

var readHtml = function (fileName, res) {
    fs.readFile(__dirname + '\\' + fileName, 'utf8',
        function (err, data) {
            if (err) {
                // Handle exception...
            } else {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.end(data);
            }
    });
};

var server = http.createServer(function (req, res) {
    switch (req.url) {
        case '/about.html':
            readHtml('about.html', res);
            break;
        case '/index.html':
        case '/':
            readHtml('index.html', res);
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.end('<h1>404 - Page not found!</h1><p>What were you even trying to do...?</p>');
            break;
    }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

So, all fixed, right? Well, actually, this looks more like Nope.js! Well alright, I suppose it’s not that bad, but once your app starts to get bigger this approach might get a little messy. Let’s add some Express and see how it can help make things easier.

Just a little remark on the 404 HTML. Of course it would be better to create another HTML file for the 404 page, but I just wanted to show you that you can use multiple methods of returning HTML even if you’ve already used another method.

Adding some Express

In the first part of this series we’ve installed Express in our project, so I’m assuming you’ve got it set up. As said Express just makes working with Node.js a lot easier. It handles routing, rendering of HTML, sessions, template engines and all that stuff. So let’s rewrite the above code so it uses Express.

var express = require('express');
var app = express();

var options = {
    root: __dirname
}

app.get(['/', '/index.html'], function (req, res) {
    res.sendFile('index.html', options);
});
app.get('/about.html', function (req, res) {
    res.sendFile('about.html', options);
});
app.get('*', function (req, res) {
    res.send('<h1>404 - Page not found!</h1><p>What were you even trying to do...?</p>'); 
});

var server = app.listen(1337, '127.0.0.1');

First we’re requiring Express. This actually doesn’t return an object, but a function, also called the express function, and as you can see on the second line we just run the function and store the result in our app variable. This app variable now denotes our Express application. After that we use the app.get function multiple times to handle our routing. I think it’s pretty straightforward. If “/” or “/index” are requested we return the index.html file, if “/about” is requested we return the about.html file and if anything else is requested we send back the 404 HTML.
It’s worth mentioning that the send and sendFile functions set the header of the response object. sendFile sets the header based on the file extension (in these cases .html) and you can override it in the options object. We only use the options object to set the root of the files though, in our case that’s the same folder as our app resides in, but for bigger projects it would be wise to create a /views folder or something like that.
Finally we call app.listen and pass in our port and IP address. Notice I’ve used the same port and IP as the nope.js example, so you can’t run them both simultaneously.

Here’s another thing Express handles pretty well. Parameters and queries. Using the request object we can ask for any parameter or query that the user sent our way. Here a little example.

app.get('/echo.html', function (req, res) {
    res.send('<h1>Echo</h1><p>This is an echo... ' + req.query.say + '</p>');
});

Using the query object we can get the value of any query parameter. In this case we expect a parameter called “say” and its value will be echoed to your browser. So just browse to localhost:1337/echo.html?say=someValue.
Pretty neat, right?

There are some other best practices, like putting your routing in a separate file and exception handling, that we haven’t discussed yet. No problem, since we’ve only scratched the surface anyway. Don’t worry, we’ll go in a little deeper yet in my next post!

And as always I’d like to give you some reading recommendations. Syncfusion has an awesome free ebook on Node.js, Node.js Succinctly. Just sign up and get them free Succinctly books! They have lots more, like JavaScript Succinctly and HTTP Succinctly, which might come in handy when working with Node.js.
And it also just so happens that Manning Publications has quite a few books on the MEAN stack as well! They’re not free, but when you really want to do some Node.js heavy lifting I can really recommend getting one of them. So they’re Node.js in Action, Node.js in Practice and Express.js in Action.
And, of course, you could also just keep following my blog, which is free and a lot less to read.

Stay tuned!

Knockout.js for data binding in HTML and JavaScript

Hi there, and welcome to another article on web development. This week we’ll be looking at Knockout.js, an MVVM library that makes data binding in HTML and JavaScript a whole lot easier. If that meant nothing to you don’t worry, that’s what I’m here for. If you’re unfamiliar with HTML and/or JavaScript I suggest you follow my series on starting web development. You can find the first part here: Web development #1: Internet and the World Wide Web.

If you like my blogs please subscribe. You can enter your email at the top right corner of this page. Don’t worry, I’m not going to sell you anything, but you’ll get new posts in your mailbox as soon as I post them.
Also, if you haven’t done so yet, make sure to follow me on Twitter @sanderrossel for other interesting articles and industry updates.

All the examples for this blog are published on my GitHub account. You can get them at the knockout-blog repo.

So with that out of the way, let’s get started!

Knockout.js basics

So what exactly is this Knockout.js? Simply said Knockout links data, from your JavaScript, to your HTML page and updates that data if it changes, either from your page (by user action) or in your JavaScript. This linking is called binding.
As mentioned Knockout is an MVVM library, which stands for Model View ViewModel, but that still doesn’t tell us much. Well, look at it this way, you probably have data to show on your page, this is your Model. This can be anything, like user information, blog posts or a list of sales orders. Your HTML page is your View, it’s what people see. The ViewModel is an abstract intermediary that communicates between your View and your Model. The key for this communication is a binder, a component that takes care of this communication.
So that sounds pretty abstract and difficult, right? Here’s the good news though, you can pretty much forget about it. The takeaway is that MVVM enables for a separation of your View (user interface, or (G)UI) and your domain data and logic. That also means you can, theoretically, rewrite your entire View without having to touch your domain. And it means one person can be writing the View while another is working on the business logic, boosting a team’s productivity. The Windows Presentation Foundation (WPF) is another example of MVVM.

So Knockout is an MVVM library, but what does this mean for us developers? How about an example? Of course we’ll need an HTML page and some JavaScript. That’s all, so I’m not going to incorporate a back end. I did, however, make use of jQuery, to show the real strength of Knockout. So I’m going to show two input fields where you can enter your first and your last name. Whenever you change either your first or last name your full name is shown below the inputs. Easy as pie. First you’ll need to get Knockout and jQuery. Head over to the Knockout download page (version 3.3.0) and the jQuery download page (version 2.1.3) to get them. Of course if you got the source from my GitHub you’re already good to go. So here’s the HTML.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Knockout example</title>
    </head>
    <body>
        <div>
            <h2>jQuery form</h2>
            <p>First name: <input id="firstName" /></p>
            <p>Last name: <input id="lastName" /></p>
            <h2>Hello, <span id="fullName"></span>!</h2>
        </div>
 
        <div>
            <h2>Knockout form</h2>
            <p>First name: <input data-bind="value: firstName" /></p>
            <p>Last name: <input data-bind="value: lastName" /></p>
            <h2>Hello, <span data-bind="text: fullName"></span>!</h2>
        </div>
 
        <script src="jquery-2.1.3.min.js"></script>
        <script src="knockout-3.3.0.js"></script>
        <script src="HelloWorld.js"></script>
    </body>
</html>

And here’s the HelloWorld.js.

$(function () {
    // Doing our own 'binding' using jQuery.
    $('#firstName').change(function () {
        // Doing some DOM stuff to get the values...
        var fullName = $(this).val() + ' ' + $('#lastName').val();
        $('#fullName').text(fullName);
    })
    // Manually setting the initial value.
    .val('Sander');
    
    $('#lastName').change(function () {
        // Doing some DOM stuff to get the values...
        var fullName = $('#firstName').val() + ' ' + $(this).val();
        $('#fullName').text(fullName);
    })
    // Manually setting the initial value.
    .val('Rossel')
    // Trigger the change event to update the fullname.
    .change();
    
    
    // Knockout binding!
    var person = {
        firstName: ko.observable(''),
        lastName: ko.observable('')
    };
    
    // Set the values, notice that they're functions!
    person.firstName('Sander');
    person.lastName('Rossel');
    // Compute full name.
    person.fullName = ko.pureComputed(function() {
        return this.firstName() + " " + this.lastName();
    }, person);
    ko.applyBindings(person); // This makes Knockout get to work
});

So that’s a lot of code! Let’s break it down. The HTML for the jQuery form is simple and straightforward, so let’s skip that. The HTML for the Knockout form has some weird stuff though, what’s all this data-bind? This is a custom Knockout attribute (all custom HTML5 attributes have the data- prefix) that defines what attributes on the HTML element should bind to what properties on your binding context (we’ll see that in a minute). The binding then makes sure that any changes in your form are reflected in your data and vice versa. So, for example, the input that takes your first name has its value attribute bound to some firstName property on the binding context. The syntax for the binding is “name: value [, anotherName: someValue]”. We’ll see a couple of different bindings throughout this post.

Now if we look at the JavaScript we first see the jQuery implementation. This makes us select the #firstName and #lastName elements, get their value and then update the #fullName element. It’s just all DOM traversal really, nothing special about it. Now the Knockout implementation is something different! We define an object (which is really our ViewModel) with a firstName and a lastName and we assign to them whatever ko.observable(initialValue) returns. And here is the trick, really. These observables notify our page when a change is made.
After that I’m setting the values for firstName and lastName. I could’ve done that right away, but I want to emphasize that firstName and lastName are not simply our first and last names (strings), but they are actually functions (because that’s what ko.observable() returned). Changing them will require us to invoke that function and passing in the new value as a parameter. Likewise, getting the values requires us to invoke these functions, but passing in no parameters.
After that I’m giving person its fullName property, assigning to it the return value of ko.pureComputed(function, this). I didn’t specify it in the object literal, because ko.pureComputed() takes a parameter that serves as this. In the object literal I can’t use person just yet, because we’re creating it and the this will be the window if I’m not specifying it. The computed value keeps track of all its bindings (firstName and lastName) and updates automatically when one of them changes.
Last, but not least I’m calling ko.applyBindings(context) and pass it our person object. This sets the binding context and will cause our page to be updated and show the values of our person object.

I don’t know about you, but I’m not so excited about that pureComputed… So let me give you a little alternative to creating that person using a function and a constructor.

var Person = function(firstName, lastName) {
    this.firstName = ko.observable(firstName);
    this.lastName = ko.observable(lastName);
    this.fullName = ko.pureComputed(function() {
        return this.firstName() + ' ' + this.lastName();
    }, this);
}
var person = new Person('Sander', 'Rossel');

Better, no?

So that’s a whole lot to take in and with a few lines of jQuery you can get the exact same result! So why then would we use Knockout?

Building a contact form

Well, first of all, with jQuery you need to manually update variables in memory and values on your page. With just a name this isn’t a big deal, but what if you had an entire contact form? Let’s create one using Knockout. You should see that our JavaScript code isn’t growing much bigger, while this would be quite a hassle using jQuery. So here’s some contact form HTML.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Knockout example</title>
    </head>
    <body>
        <div>
            <h1>Contact</h1>
            <p>First name: <input data-bind="value: firstName" /></p>
            <p>Last name: <input data-bind="value: lastName" /></p>
            <p>Email: <input type="email" data-bind="value: email" /></p>
            <p>Subject: <input data-bind="value: subject" /></p>
            <p>Your question: <textarea rows="5" data-bind="value: content"></textarea></p>
            <p><button data-bind="click: submit">Submit</button></p>
        </div>
 
        <script src="knockout-3.3.0.js"></script>
        <script src="ContactForm.js"></script>
    </body>
</html>

And here’s the ContactForm.js.

var form = {
    firstName: ko.observable(''),
    lastName: ko.observable(''),
    email: ko.observable(''),
    subject: ko.observable(''),
    content: ko.observable(''),
    submit: function() {
        alert("You entered:"
            + "\nFirstname: " + this.firstName()
            + "\nLastname: " + this.lastName()
            + "\nEmail: " + this.email()
            + "\nSubject: " + this.subject()
            + "\nContent:\n" + this.content());
        }
};

ko.applyBindings(form);

Now that’s looking more like it! We simply create some object, bind it to our form and we have nothing else to worry about. Notice that I bind the click event of the button to the submit function, this is called the click binding.
Now here you should see some real gain from Knockout! Look at that code, it’s just an object and when submit is called we have the most recent values. No need for any DOM traversal on our side. The beauty is that you can use this form obect anywhere in your code and nowhere do you have to worry about getting the correct values from- or updating the correct values to the DOM.

Arrays and foreach

So what if we have an array of items and we want to bind to that? Luckily Knockout has an observableArray which makes this pretty easy. So let’s say we have an array with Album objects. Each album has an artist, name and genre. If we’d create a table it may look like this.

<table>
    <thead>
        <tr>
            <th>Artist</th>
            <th>Name</th>
            <th>Genre</th>
        </tr>
    <thead>
    <tbody data-bind="foreach: albums">
        <tr>
            <td data-bind="text: artist"></td>
            <td data-bind="text: name"></td>
            <td data-bind="text: genre"></td>
        </tr>
    </tbody>
</table>

So albums is just an observableArray, which is created in much the same way as a regular observable. We can simply bind an observableArray using the foreach binding. The artist, name and genre in the data-binds are called on the current object in the foreach.

So let’s say we want to provide some edit, add and remove functionality so we can manipulate our list and albums. Actually that’s not much harder!

<table>
    <thead>
        <tr>
            <th>Artist</th>
            <th>Name</th>
            <th>Genre</th>
            <th></th>
        </tr>
    <thead>
    <tbody data-bind="foreach: albums">
        <tr>
            <td><input data-bind="value: artist" /></td>
            <td><input data-bind="value: name" /></td>
            <td><input data-bind="value: genre" /></td>
            <td><button data-bind="click: $parent.remove">X</button>
        </tr>
    </tbody>
</table>
<button data-bind="click: add">Add</button>

So the click of the button in our grid is calling the remove function on our $parent object, where $parent is the container of our array. There are other such variables, such as $data (the current object) and $index (the current index).
Notice that the add button simply calls the add function, which is on our current binding context outside of the foreach loop.
Let’s look at the JavaScript for both examples.

var Album = function(artist, name, genre) {
    this.artist = ko.observable(artist);
    this.name = ko.observable(name);
    this.genre = ko.observable(genre);
}

var ViewModel = function() {
    var self = this;
 
    self.albums = ko.observableArray([
        new Album('The Beatles', "Sgt. Pepper's Lonely Hearts Club Band", 'Rock'),
        new Album('Led Zeppelin', 'Led Zeppelin III', 'Rock'),
        new Album('The Prodigy', 'The Fat Of The Land', 'Dance')
    ]);
 
    self.add = function() {
        self.albums.push(new Album());
    };
 
    self.remove = function() {
        self.albums.remove(this);
    };
};

ko.applyBindings(new ViewModel());

So first I’m simply defining the Album object. After that I’m creating a container for our array and our add and remove functionality. The first thing you’ll notice is that I’m making a reference to this by storing it in self. That’s a little weird JavaScript thing, which is nicely explained in this article: Getting Out of Binding Situations in JavaScript. Basically the remove function will not be called in the context of your ViewModel.
So after that we’re creating an observableArray (notice how it’s much the same as a regular observable). And then we have an add and remove function. We can then create a new instance and apply the bindings to our context.
You will notice that if you put both tables in your HTML (like I did) that the read-only table gets updated when you update the editable table. How awesome is that? And in your JavaScript all albums are, of course, automatically synced.

So one more thing, let’s say you can’t use a foreach binding because you don’t have a container, like a table or list. Knockout has a solution for this scenario too.

<ul>
    <li><h3>My favourite albums list!</h3></li>
    <!-- ko foreach: albums -->
        <li><span data-bind="text: name"></li>
    <!-- /ko -->
</ul>

And even that one automatically syncs when an album is changed, added or removed.

Other bindings

So you’ve now seen some of the most important features of Knockout, but there’s still much more. For example, there’s the if binding, which looks a lot like the foreach binding.

<p><input type="checkbox" data-bind="checked: showText" />(Un)check me</p>
<p data-bind="if: showText">This is the if binding.</p>
<p data-bind="visible: showText">This is the visible binding.</p>

<!-- ko if: showText -->
    <p>This is the commented if.</p>
<!-- /ko -->
var ViewModel = function() {
    this.showText = ko.observable(true);
}

ko.applyBindings(new ViewModel());

Next to the if binding there is a visible binding in there. Notice how the three act the same, but are actually different. You can check that when you press F12 in your browser and check the page’s HTML when you check and uncheck the checkbox. While the visible binding simply sets the style of the paragraph to display: none, the if binding removes the element from the DOM.

The attr binding let’s you set any attribute of an element. Here are some examples.

<p><input type="email" data-bind="attr: { placeholder: emailPlaceholder }" /></p>
<p><a data-bind="attr: { href: url, title: urlTitle, target: urlTarget }">This is a link.</a></p>
var ViewModel = function() {
    this.emailPlaceholder = ko.observable('example@contoso.com');
    this.url = ko.observable('http://sanderrossel.com');
    this.urlTitle = ko.observable("Sander's bits");
    this.urlTarget = ko.observable('__blank');
}

ko.applyBindings(new ViewModel());

The attr binding has a little weird syntax. Basically you specify attr: and then a literal JavaScript object with the attributes as properties and the fields you want to bind to as values.
In this example, since none of the values are going to change anyway, you could opt for not making the values observables, which is perfectly valid and which will show your data correct (but, of course, will not update when the values are going to change).

How about dynamically adding and removing classes to your elements? We can do this using the css binding. It looks a lot like the attr binding, except we now specify the class we want to add and the condition when it should be added (of course you should add some CSS too, if you’re using my files from GitHub you’ll see a little embedded CSS in the header).

<p data-bind="css: { cool: temperature() <= 7, moderate: temperature() > 7 && temperature() < 20, hot: temperature() >= 20 }">Temperature: <input data-bind="value: temperature" /></p>
var ViewModel = function() {
    this.temperature = ko.observable(15);
}

ko.applyBindings(new ViewModel());

You can also set your style directly using the style binding. I’ll leave that for you to figure out on your own.

Templates

So there’s one last very powerful feature I want to discuss, templates. So let’s go back to our album example. We now displayed them in a table, but what if we wanted to create regular inputs, perhaps create a little card view, instead of rows. You could use the comment style foreach, but what if you wanted this on other pages as well? You’d have to copy-paste your HTML onto the other page. Knockout has a better solution, the template binding.
So the idea is that you create some HTML which isn’t part of any page. We’re going to inject this HTML into our page, once for each album. And we can inject it on other pages too, if we want. It’s basically HTML re-use. So we can use the same JavaScript that we used in the arrays example. Here’s the HTML.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Knockout example</title>
    </head>
    <body>
        <div>
            <h1>My favourite albums</h1>
            <div data-bind="foreach: albums">
                <div data-bind="template: { name: 'album-template', data: $data}"></div>
            </div>
        </div>
 
        <!-- This is our template -->
        <script type="text/html" id="album-template">
            <h2 data-bind="text: name"></h2>
            <p>Artist: <span data-bind="text: artist"></span><br>
            Genre: <span data-bind="text: genre"><span></p>
        </script>
        <script src="knockout-3.3.0.js"></script>
        <script src="ArraysAndForeach.js"></script>
    </body>
</html><!DOCTYPE html>

So we’re looping through our albums using the foreach binding. Then for each album we inject the template, which gets the current album as its binding context ($data). As you’ll see the template is now inserted in our page once for every album. Pretty awesome!

Well, that’s it! I hope I could make Knockout.js a little easier for you. I won’t say it’s easy, because I’ve had my share of problems with it too. Luckily it’s all worth it in the end, since Knockout can make your life a lot easier and your code a lot more concise.
I should probably mention that Knockout wasn’t created as a replacement for jQuery, or any JavaScript library for that matter, and you can use Knockout with other libraries if you like.
Knockout has more to offer, I can especially recommend that you take a look at the Mapping plugin, that can create observable objects from regular objects. Other than that the Knockout website has a pretty nice tutorial and the documentation is pretty good too, so be sure to check them out. And again I’m going to recommend a free ebook (all you have to do is sign up) from SyncFustion, Knockout.js Succinctly (I swear I don’t owe any SyncFusion stock! 🙂 ).

Happy coding!

Twitter Bootstrap for responsive, mobile first web apps

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 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! 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) . "rn", 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 (rn, 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!