Tag Archives: CSS

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": "https://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!

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="https://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="https://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 #8: Where to go from here

So if you’ve read all of my previous posts and you’ve made it this far congratulations! You’ve now learned the basics of web development and you have the knowledge to create awesome websites. To actually create awesome websites you need skills and skills come from practice and experience. I’ve only touched the surface in this blog series. So it’s now up to you to get your hands dirty and write more HTML, more CSS, more PHP and more JavaScript. And while doing that Google is your friend! I’ve far from discussed all the possibilities (people write entire books about that), but at least you know all the moving parts. So these previous blogs weren’t so much about making you a pro, they were about getting you up to speed in a simple manner. The rest, unfortunately, is up to you. In case you’ve missed some posts, here they all are again.

  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 what’s left for us? Well, in this post I’ll write about some stuff I haven’t written about in the previous posts, but which every web developer should know about. After that I’ll lay out some alternative technologies for you that may help you get started with the technologies you want.

Debugging

So you’ve written your page, you test it in your browser, and for some reason it doesn’t do what you want it to do. How can we find our error? The examples I’ve given were pretty small and in those cases it may be feasible to just have a good look at your code again. However, when you’re going to write large applications with much more code on both front- and back end just looking at your code isn’t going to help you. I haven’t discussed debugging your code because a lot of it depends on your environment. In this series I’ve used Notepad++ which doesn’t have any debugging capabilities (although I read there’s some plugin that let’s you debug code, I haven’t tried it though). If you’re going for an IDE (Integrated Development Environment) such as Visual Studio, Eclipse, NetBeans or XCode you’ll get a lot more possibilities. You can set breakpoints, for example, which allows you to pause your software on a certain line of code and inspect variables and their values and then even step through your code line by line to follow the flow of your code. Personally I work with Visual Studio and it allows you to see the entire stack and even edit code at run time.

But that’s all back end debugging. What if something is wrong with your CSS, HTML or JavaScript? Luckily all major browsers (and probably the non-major too) have debugging support. If you’re in IE, Firefox or Chrome press F12 and you’ll get the developer tools (alternatively you can look them up in the browser’s menu). So here you should see a tab or button that gets you to the console. In the console you’ll see any errors or warnings that are generated by your page (invalid HTML, a bug in your JavaScript, etc.). You can also log to the console yourself using console.log() in your JavaScript (never ever use that in production code though). There’s also a tab called Network where you can see all server requests from your page. This comes in handy when pages load slow, perhaps you’re making a lot of requests or you’re loading some large file that takes a while to load. There’s also a tab where you can see your page’s HTML and CSS and edit them real-time (in your browser, not on the server). You can either select an element in the DOM and have it light up on your page or select something on your page and have it highlighted in the DOM. Then you can make changes to your HTML and CSS and see the results real-time. It’s also possible to debug your JavaScript. You can set breakpoints and step through the code following the execution flow and inspecting your variables. Pretty neat and indispensible when working on your pages! Try working with the developer tools in your browser of choice and look for some tutorials.

Picking a back end language

In this series I’ve used PHP. PHP is free (although most languages are nowadays), easy to start with and supported everywhere. You can simply open up Notepad(++), start typing PHP, put it on your server and it’ll run. Compare that to other (compiled) languages like Java and C# and PHP is an absolute winner. A lot of popular Content Management Systems (CMS), applications that help in creating, editing, publishing and maintaining content on your websites, such as WordPress, Joomla!, Drupal and Magento, have support for PHP too. So PHP is a good choice for many applications.

However, a lot of people prefer their languages more strongly typed and object oriented. In that case you might go for Java or C# (or Visual Basic). So suppose you want to go for C# because perhaps you already have experience in WinForms or WPF or a client wants a .NET application. So when using C# you’re basically using the .NET Framework and when going for web development you’ll be using the ASP.NET stack. But then in ASP.NET you’ll have some options like WebForms and MVC. Let’s go with ASP.NET MVC, because that’s a good choice for modern web development. ASP.NET MVC makes use of the MVC Design Pattern. MVC stands for Model View Controller. When requesting a page ASP.NET MVC basically calls a method on a class. This class is called the Controller. Perhaps your Controller makes some database calls and does some computations and then comes up with the data that you want to show on your page. This data is just another class and represents the Model. The Model is then passed to your View, which is basically your HTML, which is then returned to the client. And, like PHP, with C# (or Visual Basic) you can generate HTML/View using the Razor Engine.
So you want to get started with ASP.NET MVC? I don’t blame you, it’s a great product. I recommend you get the Visual Studio Community Edition for free and just start! There’s plenty of tutorials on the web, but if you’re looking for a more structured course on MVC I can recommend the book Professional ASP.NET MVC 5.
And here’s a little downside to .NET compared to PHP. Once you have your software ready for production you’ll need a server with .NET installed that’s also running some special server software called IIS (Internet Information Services).

Another alternative to PHP and C# is Node.js. Node.js is relatively new and is a fast and lightweight platform that allows you to run JavaScript in your back end and create real-time web applications. So you can use JavaScript in your back end, which is pretty neat because that means you can re-use code from your back end in your front end! Try doing that using any other back end language. Other than that Node.js uses sockets, which enables it to send data to your client without that client asking for it. Usually a client sends a request and the server serves. But now we can serve without the client having to request! That allows us to easily create, for example, a chat application. Our client simply subscribes to the chat and our server sends every new message to the client as soon as it’s received. So when going with Node.js you probably want to use Express as well. Express is a JavaScript framework for Node.js which makes working with Node.js just a bit easier. And when you want to start using sockets extensively you might want to check out Socket.IO, which is a library for working with sockets from JavaScript. And of course you’ll need to generate your HTML in Node.js. There’s a few options for you, but Jade is a pretty popular one.
So you may have figured out some of the downsides of Node.js. First of all, it’s JavaScript, which may or may not be a problem for you, depending on your tastes. Second, unlike C#, Node.js doesn’t “just work”. To get any serious business done you need quite some external JavaScript libraries (and there’s A LOT as we’ll see in a bit). The pro, of course, is fast, relatively easy, real-time web apps using the same language as your front end.
If you’re interested in Node.js you may take a look at what’s called the MEAN stack, MongoDB, Express, AngularJS and Node.js. It’s free, open-source and very JavaScript.

I should probably mention that .NET has their own sockets framework that allows you to build real-time web apps easily, called SignalR.

So we’ve looked at some alternatives to PHP. There are more, like Ruby (On Rails), Python and Java. You can check them out, read a bit about them, and decide what works well for you.

Some front end alternatives

So we’ve looked at some back end alternatives, but what can you do on the front end? On the front end it really all comes down to HTML, CSS and JavaScript. Your HTML is generated on your back end and there’s plenty of options to do it, like Razor, Jade or any other HTML generator. It all depends on what back end you pick.

So what about CSS? Well, browsers really require CSS to lay out your page. There are some alternatives though, most notably LESS.
LESS looks a lot like CSS, but adds some features. You could almost call it object oriented CSS.
Another alternative is Stylus, which, like LESS, adds features to CSS. Stylus is focusing more on expressive CSS, which is easy and clean to read while also supporting some form of object orientism.
There’s more, like Sass and Turbine.
Now here’s the deal. None of them replace CSS, rather they are compiled to CSS. So you write your LESS (or any other), compile it, then use the generated CSS on your page. This adds some hassle, since you need to compile your code (your not-quite-CSS) before you can actually see it on your page (as opposed to just refreshing your page). But they also make for clean, maintainble CSS. I recommend checking out at least one of them, especially when you’re going to build larger websites. Alternatively you can just use an already existing library, such as Twitter, which I’ll talk about in a bit.

What about alternatives for JavaScript? There are quite some languages that compile to JavaScript. The two most notable are probably TypeScript and CoffeeScript though.
When you read the first lines on the CoffeeScript page you’ll pretty much have an idea what CoffeeScript is all about, “JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way”. So there isn’t much to say about that. It’s just a new syntax for JavaScript, hiding the dirty bits. I haven’t used it myself, but if you don’t quite like the JavaScript syntax and want to try something that’s like JavaScript, but prettier you might want to check out CoffeeScript.
Now TypeScript, that’s quite something different. It adds type safety to JavaScript and actually reads more like C# than JavaScript. Not completely by coincidence as TypeScript was actually created by Anders Hejlsberg, lead architect of C#. Of course it still just compiles to JavaScript. If you’re already in the Microsoft stack and using Visual Studio you may as well give TypeScript a try!
I also want to mention Dart very briefly. It was created by Google and it’s a fully object oriented way of writing JavaScript. In their words “new, yet familiar”.

Libraries and Frameworks

When working with JavaScript you know everything is possible, but nothing is easy. Luckily a whole lot of people have created libraries for you that you can use when using JavaScript. In this section I just want to point out some popular libraries and frameworks. We’ve already seen jQuery and jQuery UI.
Another very popular framework is Twitter Bootstrap. It’s mostly CSS, but has some JavaScript too. It allows you to create pages that look good and scale well across devices with relative ease. It mostly depends on tagging your HTML elements correctly. I’m not going to discuss it any further here. Just know that it’s available and that it’s widely used.
Another popular library is Knockout. With Knockout you can bind your JavaScript classes to your HTML elements. So values are automatically synchronized between your HTML and JavaScript. If a user changes the value of a text field the underlying value is changed and is reflected on your page and vice versa. Again, I’m not discussing it further, just know that it exists.
Another library that you simply cannot ignore is AngularJS. AngularJS is an MVVM (Model View ViewModel) framework for building Single Page Applications (SPA). That means you get a single web page and all data is fetched using AJAX. It makes for a fluent user experience as the website doesn’t need to refresh with each request (only parts of it). AngularJS is BIG. It basically does most that jQuery does and everything that Knockout does as well and the learning curve can be steep. Luckily there are some nice tutorials and books around.
Now one of the most awesome JavaScript libraries you’ll come across is D3.js. If you need any kind of graph or table, or any visual to represent your data, D3.js is the library you need. Just look at it. The website features many examples and it’s fun to just look at it. The only thing I don’t like about this library is that I haven’t needed it yet 🙂
You might come across Ember.js as well. It’s an MVC framework for creating Single Page Applications.
Without going into detail, here are some other popular JavaScript libraries: Underscore.js, Backbone.js, MooTools, jQuery Mobile, Modernizr

There’s literally thousands of JavaScript libraries and frameworks. Some are pretty big, like Angular, and some are really small and do just one thing only, but do it really well. You might want to check out Microjs, a website with literally hundreds of very small JavaScript files. Just look around and see what’s available, it might surprise you.

Some final words

So in this final post of my web development series we’ve looked at some alternatives and libraries you can use to help you create awesome websites. There’s still lots of stuff that we haven’t covered, like putting your website in production (because that really depends on the languages you used and where you’re hosting), security (very important!) and SEO, or Search Engine Optimization. We’ve also skipped databases entirely.
We did have a look at all the parts that are vital in web development though. You should now have a pretty good idea of what you need to create your own websites.
In this series I have pointed out some books from the SyncFusion Succinctly Series, and I’m going to do so again. You can subscribe freely and gain access to free books on JavaScript, Twitter, Knockout, AngularJS, Node.js and much more. All I can say is that it’s really worth it!
For more (less succinct) books on various topics, including a lot of web development, I can recommend Manning Publications. They have some good stuff on Node.js, D3.js, SPA Design, CORS, and more.
Two other really cool articles/projects I came across are Learn JavaScript by Dave Kerr, where he creates a Space Invaders game using JavaScript and a Mario game by Florian Rappl. Both are worth checking out (and if you don’t like their articles you can still play the games 😉 ).

So that’s it for this series. That isn’t to say I’ll stop blogging or I’ll stop writing about web development, it just won’t be for this series. I hope you enjoyed it as much as I did. Any comments and questions are more than welcome!

Thanks for reading.

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 #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(https://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="https://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!