Getting Started 3: HTML – forms and tables

This is the 3rd post in the Getting Started series.

In this post, I will be introducing more HTML elements, mainly the form and table elements.

HTML forms

For forms, the two main attribute are action and method. action tells the form where to submit the values, and method tells the form how to sumbit the form, the value can be either GET (default) or POST. If you have no idea what I am rambling about, read the rest first, then head over to this article to get it all sorted out.

What’s more important here is the form elements. These comprises everything that makes up a form. When rendered, the browser will display the form with the different field, depending on the element used.

Each element will have the tag name and it would correspond to the different fields in the form (eg. ’email’ and ‘password’ for a login form).

input (the fundamental one)

This is the one you probably will use the most often. The input element is usually accompanied by a type tag. For those usual text input that you see on most forms, the type value is text, but there are other types of inputs too, like number and date, just to name a few.

One commonly used input will be the password typed input. Instead of displaying the text, asterixs are used instead to hide the input text from prying eyes.

Most input type will also have the placeHolder attribute. For modern browsers, the placeHolder value will be displayed when the value of the input is empty.

input (the special kind)

There are some special kinds of input too. When the input is typed submit, a button will be rendered to submit the form where the input resides in.

There is also a type hidden for input tags. This tag will not be displayed and is usually used to submit “behind-the-scene” information that users do not need to enter directly.

textarea (the bigger text input)

For form inputs which are longer (eg. addresses, paragraph of text), there is the textarea element. This element allows for multiline text input. For long input, the textarea is usually used.

option (the dropdown list)

In some inputs you only want to give your users a few options (their month of birth for example).

So you make use of option and select to create the dropdown list they can choose from. select is the tag that encloses the different options, in the aptly named tag, option.

radio buttons (choosing between options)

This is another way of allowing your users to choose from different options. When using radio buttons, all the options are shown, as compared to dropdown lists, where the options are revealed only after a click. Radio buttons are displayed when input are typed radio and are activated when the attribute checked exist for the element.

checkbox (either on or off)

For this element, it used for fields where there is only two choices (eg. ‘remember password’ for a login form) — selected or not. A checkbox is displayed when an input is typed checkbox.

HTML5 inputs (specialized pickers)

As I mentioned before, the input tag is the mother of all inputs. In HTML5, there are some new types of inputs that triggers specialized pickers for choosing (eg. colors, dates). There is really too many types to go through throughly here. Visit this article to view the kinds of input available for use.

input (the expansion pack)

Of course, everything is flexible in frontend development. With sufficient knowledge in styling and javascript, almost everything is possible.

Libraries such as AnyPicker and jqueryUI extends the form functionality of existing browsers by providing even more specialized pickers for different form fields. Anyone interested should go and check them out.

sample (basic HTML forms)

<form>
    <input name='input_text' type='text' placeHolder='text input' />
    <input name='input_hidden' type='hidden' value='not_be_shown' />
    <textarea name='input_textarea' placeHolder='textarea'></textarea>

    <select name='input_select'>
        <option>Option 1</option>
        <option>Option 2</option>
    </select>

    <div class="'radio'">
        <div>
             Option 1
        </div>
        <div>     
            Option 2
        </div>
    </div>

    <div>

        Yes or No
    </div>

    <input type='submit' value='Click Me' />
</form>

rendered:

tables (displaying information)

Most data are displayed in tabular format, it allows the users to quickly see the relation between the different entities and compare data more efficiently.

The tables in HTML are enclosed in the table tags. Within the section, all the information will be formatted by its row and column.

tr & td (basic table elements)

For tables, the most important thing will be the rows and columns. In HTML, the rows are represented using the tr tag and the column, using td tag.

thead and tbody (table styling)

When displaying data, the headings are very important. In HTML, the headings and the data itself is separated using the thead and tbody tags. This way, the headings can be styled separately from the rest of the table.

additional data formatting

Sometimes, tables are not as simple as they seem. In more complex arrangement, a single table cell could span over multiple rows or columns, and this is where colspan and rowspan comes in. Read this article to have a better understand of how to use those attributes.

sample (basic HTML tables)

<table>
    <thead>
        <tr>
            <td>Index</td>
            <td>Name</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>01</td>
            <td>Metta Ong</td>
        </tr>
        <tr>
            <td>02</td>
            <td>Alex Malcolm</td>
        </tr>
    <tbody>
</table>

rendered:

end

Now, here is the end to the third part of the get started tutorial series. In the next few tutorials, you will be working on CSS styling and JavaScript coding.

Tutorial – Making a game in SVG

Introduction

One of chrome’s best easter egg is the offline side scroller dino game. In this tutorial, I will be teaching you how to recreate a simplified version of it in SVG.

For this project, we will be using handlebars library to draw updates to the screen as it scrolls along.

note: the javascript in this tutorial is incomplete (i.e. each section only contains the relevant parts). To view the full code, visit the codepen.

Setting up the canvas

For a start, we will setup the code to render the SVG. We will only display the ground and the dino for now.

Every game will have a update loop to make the necessary movements and redraw the display. Our update loop will contain the code to render the game’s SVG figure.

This update loop is usually accompanied with a fps variable, indicating how long apart each update function call is.

// gid is shortcut for document.getElementById
var template = Handlebars.compile(gid('template').innerHTML);
var base = 280;
var fps = 20;

var data = {
  dino_y:base 
};

function update(){
  gid('game').innerHTML = template(data);
}

The handlebars template for generating the game contains only the background, floor and the dino, as of now.

<svg viewBox="0 0 800 400">
  <style><![CDATA[
#bg{
  fill:#66F;
}

#dino{
  fill:#0FA;
}

.obj{
  fill:#0F0;
}

text{
  fill:#FFF;
  font-family: Helvetica, Arial, Sans-serif;
  font-size: 40px;
  font-weight:800;
}

#game{
  font-size:80px;
}
  ]]></style>

  <rect id="bg" x="0" y="0" width="800" height="400"></rect>
  <rect id="ground" x="0" y="380" width="800" height="20" fill="#FF0"></rect>
  <rect id="dino" x="80" y="{{dino_y}}" width="80" height="100"></rect>
</svg>

Making the dino jump

Implementation To receive the clicks, we will have an overlay that will spread across the screen.

The jump function is really simple, there will be 3 main variables for this function, dino_y, dino_dy, and env_g.

The first variable, dino_y stores the current y coordinates of the player. dino_dy represents the vertical speed, positive for moving upwards, negative for moving downwards. env_g is gravity. Using these 3 variables, and some simple physics, we can make the dino jump.

Here, we will be making good use of the fps variable. Each variable change will be in terms of 1 seconds, so the fps will be used to add increments of the change during each update.

var data = {
  // ...
  dino_flr:true,
  dino_jump:800,

  /* main 3 variables for jumping calculation */
  env_g:1200,
  dino_y:base,
  dino_dy:0
}

function jump(){
  /* only one jump at a time */
  if(data.dino_flr){
    data.dino_dy = data.dino_jump;
    data.dino_flr = false;
  }
}


function update(){  
  /* change in speed and position */
  data.dino_dy -= data.env_g/fps;
  data.dino_y -= data.dino_dy/fps;

  if(data.dino_y>base){
    data.dino_y = base;
    data.dino_flr = true;
  }

  // ...
}

For each update loop, an increment of x/fps is added. After 1 second, the full value x will be eventually added.

Creating obstacles

In the game, there are all these different different obstacles that will be created on the fly. This part will show you a method of generating the obstacles.

There will be 3 classes of obstacles, small, medium and large, correponding to the different obstaclesin the original game, spike, small and large cactus.

For each set of obstacles (cactus or spikes), we will have a random distance between them (between 500px to 1200px).

Then depending on the type of obstacles, there will be different number of it in each set. There will always be 3 spkies, 2 to 3 small cactus, and 1 to 2 large cactus in our game.

Of course, we will have to animate the obstacles too. For that we will have the env_dx variable to set the speed of the obstacles, which will be used in the update loop to move the obstacles along.

var data = {
  // ...
  objs: []
}

function createObjs(){
  /* staring generating from x=80 */
  var last = 80;
  var objs = data.objs;

  /* get x position of the last obstacle */
  if(objs.length){
    last = objs[objs.length-1]['x'];
  }

  /* dunnid to generate until too far */
  if(last>1200){ return; }

  while(last<1200){
    last += rand(5,12)*100;

    /* option of spike, small or large cactus */
    var opt = rand(2);
    var h = [50,100,150][opt];
    var w = [50,50,60][opt];

    /* random count of the obstacles in each set */
    var c = rand([3,1,1][opt],[4,3,2][opt]);
    for(var i=0; i<c; i++){
      objs.push({
        x:last+(10+w)*i,
        y:380-h,
        w:w,
        h:h
      });
    }
  }
}

function update(){
  /* moving existing obstacles */
  for(x in data.objs){
    data.objs[x]['x'] -= data.env_dx/fps;
    if(data.objs[x]['x'] < -500){ delete data.objs[x]; }
  }

  createObjs();
  //...
}

In the update loop, the createObjs function is called to replenish the obstacles after the past spikes and cacti have long moved off the screen, thus creating an “infinite level”.

Setting the score

For the original dino game, the score is depedent on how long you survive in the game. We will thus have another timeout just to increment the score, 10 points per second of surviving.

function score(){
  data.env_s += 1;
  window.to_score = setTimeout(score,100);
}

Colliding with the dino

Since all the objects in the game are rectangles, we can use the simple boundary box collision test.

figure for collision test

The brief idea is that the x-axis segments of the 2 bounding boxes cannot collide, same goes to the corresponding y-axis segments.

function collide(obj){
  /* player's bounding box boundary */
  var dino = {
    x1:80,
    x2:160,
    y1:data.dino_y,
    y2:data.dino_y + 100
  };

  /* object's bounding box boundary */
  var wall = {
    x1:obj.x,
    x2:obj.x + obj.w,
    y2:380,
    y1:380 - obj.h
  };

  /* simple rect obj collision */
  if(wall.x1<dino.x2 && wall.x2>dino.x1 && wall.y1<dino.y2 && wall.y2>dino.y1){
    return true;
  }

  return false;
}

function update(){
  for(x in data.objs){
    if(!x){ continue;}

    /* only check if the obstacle is close enough */
    if(data.objs[x].x<200){
      if(collide(data.objs[x])){
        // we will handle this in more detail later
        alert('lost');
        return;
      };
    }
  }
}

The collide function takes in the information of an obstacle, gets its extreme boundaries and compares it with the player’s extreme boundaries. If there is a collision, the function will return true.

Reseting the game

Time for some refactoring. To create a game that can be started and restarted over and over again, we will wrap all the initialization and the start of the update loop into a reset function.

Along with it, we should have a function to end the update loop, this will be aptly named lost. The will contain all the code for removing the timeouts and resetting the score.

function reset(){
  window.data = {
    env_g:1200,
    env_s:0,
    env_dx:300,
    dino_y:base,
    dino_dy:0,
    dino_jump:800,
    dino_flr:true,
    objs:[] 
  };

  update();
  score();
}

function lost(){
  alert('lost');
  /* can add other stuff if you want */
}

function update(){
  /* collision */
  for(x in data.objs){
    if(!x){ continue; }

    if(data.objs[x].x<200){
      if(collide(data.objs[x])){
        lost();
        return;
      };
    }
  }

  //...
}

Making it harder

There are a many improvements you can make to make the game more challenging. Here are some ideas:

  • Increase speed at higher scores
  • Increase gravity so player drop faster
  • Reduce distance between obstacles to reduce time for reaction
  • Increase the number of obstacles per set, making the obstacle set longer

As for the code, I will leave it out as an implementation exercise. Have fun!

codepen.io

Getting Started Series

The Getting Started series introduces you to fontend development. Follow these tutorials to learn the basics of web developement. With all these basics, you can make simple adjustments to your sites, add in new information on your own.

  1. Markdown – Simple formatting for documents
  2. HTML – markup language for the web
  3. HTML – forms and tables

But if you want a more complete tutorial, on how to design and implement a website design from scratch, contact ongspxm@gmail.com for more information.

Tutorial – SVG Rendering with Handlebars

Introduction

Handlebars is a javascript templating library that can be used to generate content on the fly. SVG (or scalable vector graphics) generates graphics from xml. In this tutorial, we are going to generate a figure (a SVG) to show the addition process of two two digit numbers.

SVG figure design

To align the numbers, we are going to split the numbers into their inidividual digits and then render them separately. Each digit will fit inside a 40 by 40 pixel square. And the “carry over marking” at the top, will fit inside a 20 by 20 pixel square.

The labelling of the numbers are as follows, the first row numbers start with a, so the tens place of the first number will be aa and the ones placing be ab. The tens place of the second number is ba and ones place bb. Similiar, hundreds, tens, and ones place of the answer will be ca, cb, and cc respectively.

<svg viewport='0 0 120 180' width='120' height='180'>
    <line x1="0" y1="110" x2="120" y2="110"></line>
    <text id="numbers">
        <tspan id="aa" x="50" y="60">{{aa}}</tspan>
        <tspan id="ab" x="90" y="60">{{ab}}</tspan>

        <tspan x="10" y="100">+</tspan>
        <tspan id="ba" x="50" y="100">{{ba}}</tspan>
        <tspan id="bb" x="90" y="100">{{bb}}</tspan>

        <tspan id="ca" x="10" y="160">{{ca}}</tspan>
        <tspan id="cb" x="50" y="160">{{cb}}</tspan>
        <tspan id="cc" x="90" y="160">{{cc}}</tspan>
    </text>
    <text id="marker" x="30" y="30">{{m}}</text>
</svg>

Generating the text for the diagram

There will be a form for us to get the two numbers, the first input will be id-ed a, the second input will be id-ed b. Then the button of course. The figure div will contain the final rendered SVG.

In the script, we first get the two numbers, add them up together, check whether the value will carry over. Then transform them to string, after that we will render the SVG.

function update(){
  /* shortcut functions */
  var $ = function(qry){
    return document.querySelector(qry);  
  };
  var _ = function(txt){
    return parseInt(txt);
  };

  /* getting the values */
  var a = $('#a').value;
  var b = $('#b').value;
  var c = (_(a) + _(b)).toString();

  /* transforming to text */
  var res = {};

  if(a.length>1){res.aa = a[0];}
  res.ab = a[a.length-1];

  if(b.length>1){res.ba = b[0];}
  res.bb = b[b.length-1];

  if(c.length>2){res.ca = c[0];}
  if(c.length>1){res.cb = c[c.length-2];}
  res.cc = c[c.length-1];

  /* the carry over marker */
  res.m = (_(res.ab)+_(res.bb)>9) ? '1' : '';

  return res;
}

After getting the values, we will render the SVG using handlebars library. And put the value into the #figure div.

var template = Handlebars.compile($('#template').innerHTML);
$('#figure').innerHTML = template(res);

Final product

When you put everything together, you have this. There you have it, handlebars rendering of a SVG figure.

Getting Started 2: html – markup language for web documents

This is the 2nd post in the Getting Started series.

Basic HTML

HTML(hyper text markup language) is a data representation format based on XML. It is used for formatting web documents in general, and contain all the required elements for a browser to render the tags as a website.

Basic XML

HTML(or XML in general) follows this following set of formatting and rules.

Sample XML Document (Not HTML btw)

<Document>
    <title>Hello World Page</title>
    <article author="Metta Ong">Lorem Ipsum</article>
</Document>

As seen from above, the document is formed by tags in the form of tags. Tags come in pairs, opening and closing tags. The opening tag is enclosed with a less than and greater than sign, and a closing tag has a / before the tag name.

Attributes are “descriptions” attached to the tags. In the above example, the author="Metta Ong" is the attribute attached to the article tag. Content placed between the open and close tags are actual text content of the tags.

XML hierachy is pretty simple to understand. In the example above, both the title and article tags are considered children of the Document root tag.


Main structure of web pages

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
    </body>
</html>

Main structure of web document

Different versions of HTML

There are many HTML versions out there (the most recent one is HTML5). To tell the browser which version of HTML your document is, we use the DOCTYPE tag.

So, at the top of your document, incude the following line: “. This tells the browser that your document follows the HTML5 format.

For those curious few out there, there are a few different types of DOCTYPE for HTML4 document is – strict(), transitional(), etc. You can read more about doctypes here.

Main 2 components

The head tag is the place where all the information goes. Data contained in this tag is usually not rendered. By convention, all scripts and styling goes here, together with all the information of the document, like the title, description, etc.

The body tag is the place where all the rendered information go. All your headers, navigation and content goes here.

Document information

<head>
    <title>Title of Document</title>
    <link href='/path/to/stylesheet.css' type='stylesheet' />
</head>

Example head tag

All the information will be stored here, the title of the document, all the metadata (description, author, etc). The metadata can be used for search engine optimization (SEO), it gives the browser detailed information to categorize your document (more on that in other tutorial).

While styling can be done on the main html file itself, you can also attach stylesheets using the link tag. The syntax to do so is as follows: “

You can attach things like favicons (the small tiny logos for your page). Using the link tags, these images can be attached as so:

<!-- linking a style sheet -->
<link href='path/to/style.css' rel='stylesheet' />

<!-- favicon -->
<link href='path/to/icon.png' rel='icon' type='image/png' />

Basic components

In the previous post, you learnt about formatting documents using markdown, know that you know the basics about document formatting, I will now teach you how to do all that in HTML (yeah, finally :>)

Headers

In markdown, there are different kinds of headers, representing different layers of information. The highest level of all headers have the h1 tag, it all goes all the way, from h2, h3, all the way to h6.

<h1>Usually for the main title of the page.</h1>
<h2>Subheadings. Title for the different sections</h2>
<h3>Even smaller headings, content headers maybe?</h3>
<h4>Not too sure why you would go so deep...</h4>
<h5>Probably just use this for styling purposes...</h5>
<h6>When you reach here, its time to split your content...</h6>

Paragraph text

The p tag (yeah, p for paragraph) used to contain all your text. It can be can be any kind of text, its the generic text container. It is to be embedded in the new HTML5 content tags for SEO (searc engine optimization).

Text styling

Within the paragraph tags, there are some special styling tags to basic transformation to yout text. Here are some of the basic tags available for use.

<b>bold, b for bold</b>
<strong>makes the text bold</strong>

<i>italics effect, i for italics</i>
<em>also italics effect, emphasized</em>

<u>underlined text, u for underline</u>

<mark>highlight text. yep, like a highlighter.</mark>

<s>to show cancellalation (strikethrough), really...</s>
<del>strikethough, similar to the 's' tag</del>

<sub>subscript, text written close to the foot of the text</sub>
<sup>superscript, you know like in math, the power function</sup>

<code>Shows code. text will be displayed in monotype font.</code>

For more advanced styling, you can take a look at the CSS declaration specified for text..

Images

Your pages will be boring with any visual candy. The image tags (img) contains your images. (like duh.)

<img src='http://lorempixel.com/400/200/' alt='a random image' />

Yes, img tags are one of those special kinds that do not need to be closed (because your browser most likely wont render anything enclosed by those tags).

Links

The web works like a interwoven collection of pages, and linking them together will be these a tags (a for anchor). These tags have an attribute href (hyperlink reference), which points to the location you want to redirect your readers to. And this is how you use it:

<a href='http://www.google.com' target='_blank'>
    Link to google
    <img src='path/to/img'/>
</a>

Yep, you can put images in your a tags too. Actually, you can put in anything basic tags under the sun and it will work.


Adding more structure

Most pages will have a certain page structure to it, header,content, footer, at least. The basic containers for most elements are the div and span tags.

But in html5, there are many more tags that can better segmentalized your page into the appropriate sections.

Basic containers

The most basic tags are the div and span. There are a few difference between them. div is for block elements and span is for inline elements.

Block elements refers to a whole section of the page which are displayed as blocks of content. These usually refer to section of the page, such as header, navigation bar or footer.

Inline elements as their names suggest, refers to a small portion of content, within a block to which specialized styling (usually through CSS) is applied to.

HTML5 section tags

In HTML5, there are much more section tags that helps add structure to the documents.

header is a section tag for containing the header content. It can include your logo, your page header, and whatever you plan on putting in your header section.

footer serves the same function as the header tag, a container for footer content (including copyright and contact information).

article contains the main content for the document. But if they are sections in the article, you can use the section tag to separate your content.

nav tags are for navigation. It will consist the links to the different sections of your website (home, about, etc).

aside tags are for sidebars which contain additional bits of information (description for blogs for example).

There are more of course, you can view all that here.


Special Content

In HTML5, there are many new semantics tags added to give structure to your documents.

Pre VS Code

We talk about the code tag just now. But for whole sections of codes, we use the pre tag to contain whole sections of code, preserving the newlines and whitespaces, keeping all the indentation intact.

<pre>
function add(x, y){
    return x+y;
}
</pre>

Figure

The figure tag is used to contain illustrations and pictures. The figcaption is used to add description to the figure. This all is written in the following manner:

<figure>
    <img src='http://lorempixel.com/400/200/' />
    <figcaption>
        Some random picture from lorempixel
    </figcaption>
</figure>

Audio

The audio tag is used to embed an audio resource into the page.

<audio src='test.mp3' type='audio/mpeg' />

Video

video tag is similar to audio tag, but with videos instead of audio files.

Canvas & SVG

The canvas and svg tags are used for drawing things on the page. The canvas tag is controlled using javascript. The svg tag draws using xml. Learn more about canvas and svg.


What’s next

  • Forms (text input, form submission)
  • Tables (systematic display of info)
  • Separators (line breaks)