Tag Archives: html

HTML For Semantics, CSS For Visual

The best way to learn is to teach, they say. I totally agree, and that’s one reason I have so many articles on my blog explaining random topics. Part of the goal was always to understand the topic better myself.

I got reminded of it while I was preparing for a workshop on introduction to web technologies for my fellow Berliners who wish to get into tech. Then something interesting happened. I found the root of a problem that I was struggling with for some time at work. I will jot down some notes of this entire experience, and try to tell you about the lessons learned.

Our Styleguide

We maintain a frontend styleguide (think: company-specific UI library). We have many HTML elements and CSS classes that make our text, buttons and cards look the way we want them to look across the webapps. There’s a little issue. Most textual styles are defined on HTML elements. So to get a large heading styled with our predefined font-size, font-family, color and a bunch of other styles, one would just use h1 (notice: no class needed).

This worked for us until now, and wherever a big heading was required, we would just throw in an h1. Similarly for paragraphs, lists and other textual elements. This made a lot of sense in the past as accessibility or SEO weren’t a concern. But things changed.

Multiple h1s

It all started when our contracted SEO agency told us that we had two h1s on a page. We looked at the page, and it made total sense. There were two ‘headings’ of super large size, and our styleguide’s h1 made total sense from a purely visual perspective. But the second heading was just a title in large font. It had no semantic significance. Now, our product’s main title and some random text have the same precedence on the page.

This is bad for SEO, no doubt, but this is also bad for screen readers and all mini browsers (like Apple Watch and the like) which rely on the HTML to convey semantic information, and not visual.

Thinking and problem solving

I went to our designers and had a discussion. I could just hack and overwrite the styles, but that wasn’t the point. I asked what could be done. We could change the design, create a new class the resembles heading-1s and then use that on a span and so on. But we couldn’t think of why we’ve met with this problem. Maybe we’re missing something, something obvious, we thought.

Conference on web basics

I attended a developer conference a couple of weeks ago. There we had the good fortune of listening to Hakun Lie and Bruce Lawson. What struck me, apart from how much they cared about web standards and saving the web from the bloat hell that we’re hurtling towards, is how much one can accomplish just by sticking to web standards. One of the examples used was of the Apple Watch, and the website in question was developed much before anyone imagined a browser on your wrist. If one just uses semantic HTML, one can be sure that their website would work on any device, whether in existence or yet to arrive. And just like that, millions of well-designed websites started to work on the special Apple Watch browser.

This is important to note because there are usually multiple ways of doing something on the web. More often than not, there are a couple of right and many wrong ways. Part of our job as web developers is to ensure that our website isn’t just pretty visually but also correct semantically and structurally. This is to futureproof our creation.

The workshop

I was preparing for this workshop and thinking of various ways I could introduce web development to complete beginners. I referred to some nice articles and tried to understand the meaning of HTML and CSS myself. I tried to understand why reset.css and normalize.css are used, even though I’ve been using them for years. I came up with interesting analogies to explain the basic pillars of the web and as a result, improved my understanding of these constructs.

Lightbulb moment

After the workshop, when I went back to my codebase, I could see the problem staring right back at me. We had styled the HTML elements, and not created separate classes that we could then attach to our elements. This is the result of forgetting the basics and doing something the wrong way because it saves you from writing class="" for every HTML element, which to be fair, doesn’t seem that bad when you don’t differentiate between HTML and CSS and use a combination of the two to get the design right.

Conclusion

There are a couple of conclusions for me from this article. One is to learn and follow web standards. Semantic HTML is not at all hard, just some 120 tags in total. Then, understand what a markup language means, and how the semantics of a document is different from how it looks or works. Learn the rules of CSS selectors and how cascading works. Learn that HTML and CSS are declarative, and use them as much as possible. Only where it makes sense, introduce Javascript. In general, keep abstractions to a minimum.

Thank you for reading.

CSS Crash Course

I have a friend, who happens to be a good C and assembly programmer, but simply hates anything related to web, then be it HTML, CSS or anything way too much abstracted for that matter. Since it was compulsory for us to make our own web application project for college, he struggled to learn it (CSS and HTML) from here and there, cursing it at the same time. Hence this little guide, for all those of you who hate it, but still want to get your work done.

A thing or two about CSS

CSS isn’t a markup language. It is a styling language, and hence, it won’t really work if you have no document in the first place. Creating a document simply means adding some data to HTML tags in a web page. Here onwards, document would mean the HTML page that we are working on. Let us create one as an example.

<!DOCTYPE html>
<html>
<head>
  <title>Testing</title>
</head>
<body>
  <h1>Awesome Site</h1>
  <h3>A little heading</h3>
  <p>A paragraph containing some text</p>
  <h3>Some information</h3>
  <p>More text...</p>
</body>
</html>

This is a very basic example that would display something like the following. You can guess what each tag stands for here, if not, ‘h’ tag stands for heading, ‘h1’ being the largest to ‘h6’ being the smallest. ‘p’ stands for paragraph, and there are many such tags, which are used as and when required.

Now it is time to style our document. I will place all the CSS styling in a <style> tag, which I will be placing into the <head> of the document. Now you must know that I could do the exact same thing by using an external CSS file and linking it, or by styling individual elements using inline CSS. We will see what those are later. I think the main heading should be red, the subordinate headings should be green and the paragraphs should be orange. I also think the background should be a little off white. Let’s see how that translates into CSS.

body {
  background-color: #eee
}
h1 {
  color: red
}
h3 {
  color: green
}
p {
  color: orange
}

Now that we have styled our page, let’s take another look at it.

Looks like it works, although it is looking ugly. Anyways, what we have used here is the element selector of CSS which, not surprisingly, selects the elements matching the tag name and applies the properties defined for it.

ID and Class selectors

Now, there may be times when you have multiple elements with same tag names but you want to apply CSS properties to only specific element(s). That is where the ‘id’ and the ‘class’ selector comes in. Note that however, the class here does now refer to anything from your object oriented programming books. It only gives those elements with that class a particular grouping. You can use any one of ‘id’ and ‘class’ as per your liking for now, but conventionally, we use ‘id’ for uniquely identifying elements and ‘class’ for grouping similar elements. Technically, there is an additional difference of precedence here, with the ‘id’ having more precedence than ‘class’. My personal rule is that, for custom CSS use ‘id’, since frameworks like Bootstrap (which we will check out later on) usually use ‘class’.

Now we shall rewrite the document adding an id attribute to each tag name.

<body>
  <h1 id="logo">Awesome Site</h1>
  <h3 id="heading">A little heading</h3>
  <p id="content">A paragraph containing some text</p>
  <h3 id="other-heading">Some information</h3>
  <p id="other-content">More text...</p>
</body>

and we shall change the CSS accordingly

#logo {
  color: red
}
#heading {
  color: green
}
#other-heading {
  color: olive
}
#content {
  color: orange
}
#other-content {
  color: purple
}

The resulting page looks something like this, with each of the individual elements appearing in different color.

Note that we could have well written ‘class’ instead of ‘id’ in our document, but then instead of #logo it would have been .logo, which is the class selector. Having learnt two selectors, we can now combine them to get the desired result. For example, h3#heading { color: blue; } would turn blue all the h3 tags that have a id=”heading” attribute declared. Similarly, h3.heading { color: blue; } would result in the same thing to all the h3 tags with class=”heading”.

Group selectors

Group selectors are used to apply properties to multiple elements at once. Multiple elements are separated by commas.

#logo {
  color: red
}
#heading {
  color: green
}
#other-heading {
  color: olive
}
#content {
  color: orange
}
#other-content {
  color: purple
}
/* Selecting all three tag names at once. */
h1, h3, p {
  background-color: yellow
}

Which will look like

Descendant selectors

Sometimes, CSS properties needs to be applied only to tags within a specific tag or id. In such situations, the descendant selector comes in handy.

<!DOCTYPE html>
<html>
<head>
  <title>Testing</title>
  <style>
    ul em {
      font-size: 1.25em
    }
  </style>
</head>
<body>
  <p>Look what I've <em>got for ya!</em></p>
  <p>
    <ul>
      <li>item 1</li>
      <li>item 2</li>
      <li>item 3</li>
      <li><em>this looks abnormal</em></li>
      <li>item 5</li>
    </ul>
  <p>
</body>
</html>

And this will render

Look how the emphasis at the top is normal but the one in the ‘ul’ is enlarged. There is another similar selector called the child selector. It works similar to descendant selector but demands the child to be DIRECT descendant of the parent. For example, p > a { color: green; } will cause only the anchors directly children to any paragraph to look green. These are the various selectors that you would see and probably use when dealing with web applications. Simple enough, aren’t they?

<div> and <span>

Although div and span are html tags, any modern web application that you will write will heavily make use of these to group sections of the web page together. You might be familiar with the layouts of most websites these days, with a header on top, one or two column in the center with content and other options, and a footer at the bottom. Even on my blog, you’ll notice these three things. How are they made, and how to make them look so distinct that on the first glance, your visitors know what their purpose is. The answer lies in making proper divs and adding appropriate CSS to it. Div is a block element, which means that it is used to style multiple elements at once. Span, on the other hand, is inline, that is, it is used to style little chunks of content.

I will write the 4 sections of a website I mentioned earlier, using divs. Read the code and you would understand what is happening.

<!DOCTYPE html>
<html>
<head>
  <title>Testing</title>
  <style>
    * {
      text-align: center 
    }
    #header {
      background-color: red
      height: 50px
    }
    #container {
      width: auto
      margin: 0 auto
    }
    #body {
      width: 75%
      float: left
      background-color: grey
    }
    #side {
      width: 25%
      float: right
      background-color: blue
    }
    #footer {
      background-color: green
    }
  </style>
</head>
<body>
  <div id="header"><h3>Header Text</h3></div>
  <div id="container">
    <div id="body"><p>Content goes here</p></div>
    <div id="side"><p>Sidebar</p></div>
  </div>
  <div id="footer"><p>Copyrights</p></div>
</body>
</html>

This sure looks beautiful, doesn’t it?

This completes the CSS syntax part. I did mention that you can write all your CSS in a file.css and include them in your document head with <link href="/assets/style.css" rel="stylesheet"> so that it is easier to maintain the code. There is yet another way to add CSS, which makes use of @import syntax. It is better avoided for the linked reasons.

Now that you are well equipped with the necessary things to learn some actual and practical CSS, you must be really excited to read from w3schools. It is a great site to begin, and since it comes on top each time you search for anything related to CSS (or web programming, for that matter), you may use it as your sole reference guide. Nothing bad, but keep in mind that after leaving your nutshell, you should avoid that site, and start using some reputed docs instead, like the ones from Mozilla.

CSS Frameworks

To speed up the development process, you might want to check out some libraries out there that would ease your life. One of the best is Bootstrap. It would enable you to do rapid development, with minimal typing. Bootstrap comes with jQuery, a Javascript library which also helps a lot dealing with web application stuff you are about to deal with. There is not much point reading the official docs if you only want to get the work done. Instead, I would suggest you to Google out things, pick up code on the way, keep going. That is exactly how I used to do stuff back then, when I hated to write CSS and HTML. Bad advice, but gets the job done most of the times.

Outro

CSS is amazing. Web is amazing. Today is a time when you either have to love the web, or keep fighting a losing battle convincing yourself that you don’t need it. Either way, knowing a thing or two about how the web pages that you spend more than half of your time on, are styled, is always a plus. As always, for anything, the comment box is always there. Corrections, please. Liked the article? Suggest it to your friends! Thank you for reading.

Creating Custom Blogger Template From Scratch

Although when I started with it, I hardly knew anything about a blogger template, but it turned out, designing a blogger template is easier than designing a HTML template. Just a few basic concepts and you are good to go.

Firstly, before digging into the template code, we will look at the grammar needed to code our thing. This simple article assumes you can read basic HTML, CSS and XML. Nothing above the basic level, plain simple stuff. If not, whenever you do not understand something, make sure you search that term or tag on w3schools to understand it. Yes, that’s all you really need, trust me.

Planning the layout

First of all, how do you want your blog to look like when it’s done. Just a basic idea would do. You must know what you are working for. Here is what I made. It is the way most simple blogs look like. Two column layout, a header on top and a footer at bottom.

Header
Blog PostsSidebar
Footer

Not the most interesting table, yeah I know. HTML tables, not really my thing. But this is what our end result should look like, structurally.

Basic Structure

These few lines make up a basic web page. You will see that this is quite similar to what we’re doing.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  <head>

  <body>

  </body>
</html>

And this is how a basic blogger template looks like.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='https://www.w3.org/1999/xhtml' xmlns:b='https://www.google.com/2005/gml/b' xmlns:data='https://www.google.com/2005/gml/data' xmlns:expr='https://www.google.com/2005/gml/expr'>
  <head>
    <title><data:blog.pageTitle/></title>
    <b:skin><![CDATA[ /* CSS here */ ]]></b:skin>
  </head>

  <body>
    <!-- Blog elements here -->
  </body>
</html>

Pretty neat, isn’t it? Now, the elements of a blogger blog. Blogger is built upon XHTML, and uses the same for retrieving and displaying data from the database. A basic block of a blogger template is called a section. So all of these are sections.

Header
Blog PostsSidebar
Footer

And you have to define each section before you add ‘widgets‘ to them. A basic section block looks like this.

<b:section id=' ' class=' ' maxwidgets=' ' showaddelement=' '></b:section>

where id is any unique identifier (for CSS and JS later) and class value is used to tell blogger where do we plan to place this section. Maxelements is the maximum number of ‘widgets’ we can add to this section. Generally, it is useful to limit the number of widgets in header and footer to one. Showaddelement is that ‘Add gadget’ link you see in the layout window. It takes boolean value ‘true’ or ‘false’. Now there are ‘widgets‘ that go into these sections. Every separate component that you see on your blog is a widget. The ‘blog posts’ is one widget, ‘blog archive’ is another, and so on. These widgets can be directly added from the graphical layout tab in the control panel of your blog, but it doesn’t hurt to know how to add them manually, does it?

<b:widget id="HTML2" locked="false" title="Some Title" type="HTML" />

Similarly here,

  • id – is just an unique ID
  • locked – can the widget be moved around, in the layout tab? (yes or no)
  • title – The title that will be displayed on top of the widget
  • type – One of the many basic types that blogger supports (html, blog, feed, header etc)

For example, your ‘blog posts’ widget will be something like this

<b:widget id='blog1' locked='true' title='' type='Blog' />

That’s it. Add it to the template and blogger will fill it with auto-generated code you need not care about. This was all for the basics. Let’s start with some code now. I am using Bootstrap  to save myself from writing unnecessary CSS. First thing you do here is enclose the entire body in either container or container-fluid div.

  • container – for fixed width layout
  • container-fluid – for dynamic body width

I personally prefer fixed. This is the code so far. I added container class to the <b:skin> which we can (and will) customize later.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='https://www.w3.org/1999/xhtml' xmlns:b='https://www.google.com/2005/gml/b' xmlns:data='https://www.google.com/2005/gml/data' xmlns:expr='https://www.google.com/2005/gml/expr'>
  <head>
    <title><data:blog.pageTitle/></title>
    <b:skin><![CDATA[ .container { }  ]]></b:skin>
  </head>
  <body>
    <div class='container'>
    </div>
  </body>
</html>

Now add the divs for header, post area, right sidebar and footer and corresponding CSS classes. Code trimmed for brivity.

<head>
  <title><data:blog.pageTitle/></title>
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css' rel='stylesheet'/>
  <b:skin><![CDATA[
    #container {
      max-width: 960px;
      margin: 0 auto;
    }
    #main-wrapper {
      width: 710px;
      float: left;
    }
    #sidebar-wrapper {
      width: 250px;
      float: right;
    }
    #footer-widgets {
      padding: 0px 0px 5px 0px;
    }
  ]]></b:skin>
</head>
<body>
  <div id='container'>
   <!-- Header -->
   <b:section class='header' id='header' maxwidgets='1' showaddelement='yes'>
      <b:widget id='Header1' locked='true' title='Blog title' type='Header' />
   </b:section>
   <div id='main-wrapper'>
     <!-- Blog posts area -->
     <b:section class='main' id='main' maxwidgets='' showaddelements='yes' />
        <b:widget id='Blog1' locked='false' title='Blog Posts' type='Blog' />
     </b:section>
   </div>
   <div id='sidebar-wrapper'>
     <!-- Right sidebar -->
     <b:section class='sidebar' id='sidebar' maxwidgets='' showaddelements='yes'>
       <!-- Widgets can be added from layout page -->
     </b:section>
   </div>
   <div id='footer-widgets'>
     <!-- Footer -->
     <b:section class='footer' id='footer' maxwidgets='' showaddelements='yes'>
       <b:widget id='Attribution1' locked='false' title='' type='Attribution' />
     </b:section>
   </div>
  </div>
</body>

The above code should look like this on any blogger blog.

The mobile site, I must say, would look horrible. Extra efforts are needed to make the template responsive. Since we already have Bootstrap, that is not a big deal either. I must conclude this post now, and for mobile friendly site, I may write an article soon. Also, there is no SEO in this template. You must add relevant <meta> tags to make your blog more search engine friendly. You can always override CSS rules of bootstrap by writing your own in the <b:skin> section.

Thank you for reading!

Creating an autocomplete field | Setting up the backend | Part 1

Hello folks, so my exams are over and its time to roll. LOL pretty excited here. I am creating this series of two articles in which we will download all the pincodes (or zipcodes), add them to a MySQL database, write an API in PHP to retrieve the data in JSON, and finally we will write our form, in which, when we enter a pincode, we automatically get the ‘taluka’, ‘district’ and ‘state’ fields filled. So lets begin.
(and if you are from outside India, a ‘taluka‘ is a small region, like a city)

Step 1 – Getting the Pincode list

This was my biggest concern. Where do I get a list of all the pincodes in India. I could write a script and iterate through all the possible pincodes from 100000 to 999999, but, of course, there had to be a better way (and by the way, I would have got banned by the site if I sent around a million requests in a short period of time).
Fortunately, after some googling, I found a list here, at data.gov.in, to directly download the list, click here. The data is in .csv format, which is essentially a text document with some proper ordering (LOL).

Step 2 – Setting up MySQL database

We will now add the values to a database with will serve as our source to retrieve data in the form. I am selecting MySQL because, well, that is the only SQL I currently know (wink!). I assume you know the basics of how to create a database, and even if you don’t, you can do it easily by using the  phpmyadmin. It is graphical, and will get the work done.

The columns available for inserting data are:
officename,pincode,officeType,Deliverystatus,divisionname,regionname,circlename,Taluk,Districtname,statename

I will be using only ‘pincode’, ‘Taluk’, ‘Districtname’, ‘Statename’ here to avoid any unnecessary cluttering.

Create a database: ‘turnouts’
Create a table: ‘pincode’
Create 4 columns: ‘pincode’, ‘taluka’, ‘district’, ‘state’
Needless to say, these are just names and you can have what you want, but just don’t go insane over them. This is how it should look, or similar.
Having done that, move to step 3.

Step 3 – Writing the PHP script to enumerate database

So now we need to fill those database fields with data. If you take a look, the .csv file that we downloaded has around 152,000 lines. We can insert them manually, but that would take two and a half month, so we are better off writing a script. Language is on you. Python would work, but I preferred PHP, no good reason, I just choose it.
Basically we read a line in the file, select the data that we are concerned about, generate a MySQL query dynamically in a loop, and execute the query. Then move to the next line till feof or end of file.
Here is the php code.
<?php
$file = fopen("pincodes.csv", "r") or die("Open file");
$server = "localhost";
$username = "root";
$password = "password";
$db = "turnouts";
$conn = mysql_connect($server, $username, $password);
mysql_select_db("turnouts") or die();
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
while(!feof($file)) {
$line = fgets($file);
$words = explode(",", $line);
$pincode = $words[1];
$taluka = $words[7];
$district = $words[8];
$state = $words[9];
$sql = "INSERT INTO pincode (pincode, taluka, district, state) VALUES ('$pincode', '$taluka', '$district', '$state')";
mysql_query($sql, $conn);
mysql_error($conn);
}
fclose($file);
mysql_close($conn);
?>

This code will take some time to execute. On my low end box, it took 90 minutes approx. After having executed, you should have a database with some real data. Here’s the row count, a whooping 154,797.

Now that we have our database setup, we are all set to write the front end. To make it easy to follow, I will write it in the second part of this series.

Edit: Here is the Part 2 Enjoy!

Creating an autocomplete field | Setting up frontend | Part 2

In the first part of this article, we had set up the backend MySQL database. Now we can write the code necessary to get information from the server and convert it to a format we can parse, JSON in my case here. So lets begin.

Step 4 – Writing script to get data from MySQL database

As always, we can write it in any language we are comfortable with. PHP happens to be mine. The script is straight forward, accept the pincode via a GET request, ‘pincode’ parameter. Query the database for its existence, add it to an array and using json_encode() function in PHP, display the output. If value does not exist, it will return null, and it is not our concern here about what happens after that, as it will be taken care by the application using this API.
Code: retrieve.php
<?php
$pincode = $_GET['pincode'];
$conn = mysql_connect("localhost", "root", "password");
mysql_select_db("turnouts") or die();

$pincode = (string)mysql_real_escape_string($pincode);

$sql = "SELECT taluka, district, state FROM pincode WHERE pincode = '$pincode'";
$data = mysql_query($sql);
if(!$data) {
die(mysql_error());
}
$row = mysql_fetch_row($data);
$taluka = $row[0];
$district = $row[1];
$state = $row[2];
$state = str_replace("\r\n", "", $state);
$taluka = strtolower($taluka);
$district = strtolower($district);
$state = strtolower($state);
header('Content-type: application/json');
$array = array('taluka'=>$taluka, 'district'=>$district, 'state'=>$state);
echo json_encode($array);
?> 

The URL will follow the pattern, /retrieve.php?pincode=000000 and return data. As an example, the following image,

If you have come successfully to this step, then bingo! We now have a working API.

Step 5 – Writing an AJAX form using jQuery

 We will now write a simple form with 4 fields in HTML. Include jQuery in that page, and then write the script at the bottom which will query our API asynchronously.
Code: pincodes.html
<html>
<head>
<title>Pincodes</title>
<script src="js/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="form">
<label for="pincode">Pincode:</label>
<input type="text" name="pincode" id="pincode" required /><br />

<label for="taluka">Taluka:</label>
<input type="text" name="taluka" id="taluka" /><br />
<label for="district">District: </label>
<input type="text" name="district" id="district"><br />
<label for="state">State:</label>
<input type="text" name="state" id="state"><br />
</div>
<script>
$(document).ready(function() {
$('#pincode').keyup(function(e) {
var pincode = $(this).val();

if(pincode.length == 6 && $.isNumeric(pincode)) {
var req = 'retrive.php?pincode=' + pincode;
$.getJSON(req, null, function(data) {
                 
$('#taluka').val(data.taluka);
$('#district').val(data.district);
$('#state').val(data.state);
});
};
});
</script>
</body>
</html>

Some explanation goes here.
The .keyup() event fires when a key is pressed in that field. We could have use onFocus() or onBlur() in javascript but that only fires when a field is focused or blurred, so this is much better. Since we have pincodes of length 6 digits here in India, to prevent script from querying for the first five digits, we have added a if(pincode.length == 6) to our code.

As I said, the even fires as soon as one enters the 6th digit and populates the remaining three fields with the data it retrieves.

It is hard to show it in a still image, but having just entered the pin, rest of the fields get populated.

Finally

So this was it. I hope you enjoyed it. Any corrections or suggesting, mail them to me or just comment down below. Thank you for reading.