Front End Primer

by Chris Chambers
@chrisWritesCode

Foreword

thinking like a developer...

Web development is an exciting way to create an interactive experience for people to engage in through the use of all different kinds of electronic devices. It is also a skill that can (and will) constantly challenge you while giving you visual feedback all along the way.

I learned web development by looking at the source of other websites. There were not many people in the mid 90’s that shared code... and I didn't have any books, but you could ALWAYS view the source code of any website. These days this method is a LOT easier thanks to browser features like Chrome’s Inspect Element and Firefox’s Firebug which you can use to single out any element on web page with mouse clicks. As you notice things on the web that pique your interest, you should always try to use these investigative features to your advantage!

The three languages you will be reading about are major components that every modern website is composed of. I like to compare a website to a car: the HTML is the frame, the CSS is the body and paint, and JavaScript is the engine that gives it power. With these three languages you will be able to create an immersive vehicle of information.

Wordpress (a very popular Content Management System) sites are like Crown Victorias -- friggin' everywhere and really easy to spot. There are also sites that could be compared to a rare exotic supercar... such as Amazon, or Ebay. These well-known websites have monstrous blocks of code driving their user experience.

This book will give you the basic tools needed to create a website that is somewhere in the middle. It will be search engine friendly, cross-browser compatible, and stylish. The more websites you build, the better they (and you) will get!

The internet can be a magical place and the developer is the magician and architect. We are the people that sculpt this vast landscape into wonderful interactive masterpieces. Learning the details of front-end development is a solid step in becoming a powerhouse!

Whenever I am stumped I find the toughest hurdle is knowing the right question to ask. Hopefully, this booklet will point you in the right direction.

~Chris

History of Webdev

... as I remember it

I caught a lot of flak while trying to compile this list. Many people thought I was looking for the history of the internet — I am only speaking to the history of modern web development... as I remember it. The things on this list had some kind of an impact on where we are today:

I've got lots of people to thank for helping me make this list! Andres, Dick 'n Nick, Janelle, Sam, Brad, Jon, and my Mom! If can think of something I have missed, hit me on twitter @chriswritescode.

Hypertext!

getting all marked up

HTML tags are the bones of every website. Most tags are containers and must be "opened" and "closed" by use of the less than and greater than characters -- "<" and ">" respectively. Here's the code that makes up this paragraph...

<p> HTML tags are the bones of every website. Most tags are containers and must be "opened" and "closed" by use of the <em>less than</em> and <em>greater than</em> characters... </p>

The basis of any HTML5 website looks like this:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Website Title</title> </head> <body> <!-- This is where your content will reside --> </body> </html>

Indentation is important if you or anyone else wants to be able to read your code. When you create a new nested container, always indent it (put spacing before it) to show that it is inside the parent container.

Some other tags that we will be using and modifying are:

Web semantics is the practice of giving elements logic (and therefore meaning) so that they can be understood and interpreted by machines. This is accomplished by using the correct tags in the correct places. There will be more information on semantics strewn about this literature.

Block-level Elements

Below is a complete list of block level-elements including their definitions...

Click here to show the block-level list!
address
wraps and denotes an address
article
an element that makes sense on it’s own, and could stand alone from the current document
aside
defines an element that is ‘aside’ from the parent content
audio
a sound element that can be accessed at runtime via javascript
blockquote
a section of an element that is being quoted from another source
canvas
used to draw on the screen with javascript
dd
a definition description.
div
used for elements that cannot be described semantically through use of other tags
dl
a definition list of dt and dd items
fieldset
used to group related items inside of a form
figcaption
a caption for the FIGURE element
figure
denotes self-contained content like graphs, or photos
footer
the footer of a document or section
form
holds various form elements and instructions for the website on processing values
h(n)
used to define content headings
header
used to define a header for a document or section
hgroup
used to group heading elements
hr
inserts a horizontal rule
noscript
contains html that is executed only when javascript is disabled or not present in the end-user’s browser
ol
container for an organized list
output
used to display the results of a javascript function
p
a paragraph wrapper
pre
content within this tag will be displayed in a fixed-width font, and will preserve line breaks and spaces
Section
defines sections of a document
table
defines an HTML table in conjunction with TH, TR, and TD
tfoot
table footer element
ul
container for an unorganized list
video
specifies a video element

Inline-level Elements

Below are the semantic definitions of the inline-level elements...

Click here to show the inline-level list!
b / strong
visually, these two tags work identically, though STRONG receives more emphasis when read with a screen reader
i / em
visually, these two tags work identically, though EM receives more emphases when read with a screen reader
tt
specifying teletype or monospaced font
abbr
an abbreviation; each letter will be read one at a time (asst. for example)
acronym
a word formed from the initial letters of other words; it is usually read as a word (FUBAR for example) by screen readers
cite
in HTML4, CITE was used for citations; since HTML5, it is used to denote the title of a piece of work
code
a piece of computer code; the output text will be monospaced
dfn
a definition; default styling will output the interior text in italics.
kbd
keyboard input
samp
a piece of sample output from a computer program
var
a variable
a
an "anchor" tag; a hyperlink to another file or location
bdo
bi-directional override can force text to be displayed forwards (ltr) or backwards (rtl)
br
a line break
img
references a source image and displays it
map
a cliet-side image map; different defined portions of an IMG can be linked separately
object
an embedded object (flash, pdf, java applets, video, etc.)
q
a small quotation; it will be automatically surrounded by quotation marks
script
a container for client-side script -- most often containing JavaScript
span
a semantically ambiguous container for grouping inline content; it is used when no other tag works
sub
display text as subscript
sup
display text as superscript
button
a form button
input
a form input field -- can be further defined by its "type" attribute
label
label for a form input field
select
used to create a drop-down list of selectable OPTION tags
textarea
a multi-line text input field

Check out the periodic table of HTML elements -- bookmark it, maybe!

All websites are created by using different combinations of the above elements. In the following chapters we will give your code some style (CSS) and manipulate it (JS) in front of your eyes!

Cascading Style Sheets

presentation and perception; make it sexy!

CSS is the basis of the design for your site. This is where you define the parameters of the box-model for every element in the end user's browser. You can use CSS to fine-tune positioning, sometimes regardless of the element’s position in the HTML. You can even use CSS to layer elements of your website like a photoshop file! CSS is also used to access different states of elements, like :hover for when the end-user has their positions their mouse pointer over and :active for when they are actually clicking.

CSS code blocks come in a few different flavors:

Below you can find some examples of how HTML and CSS work together.

#dog{ display: block; height: 50px; width: 100px; border: 1px solid red; } #cat{ display: block; height: 50px; width: 200px; border: 1px solid blue; } .black{ background-color: #000000; /* #000000 is hex code for black! */ } .white{ background-color: #ffffff; /* #fffff is hex code for white! */ }

Some HTML to go with our new CSS:

<div id="dog" class="black"> Spike </div>

This will draw a black box on the screen with a red outline. Setting class=”white” would make this box have a white background color instead! Let’s get a little more specific...

#spike{ display: block; height: 50px; width: 100px; } #fluffy{ display: block; } .dog{ height: 50px; width: 200px; border: 1px solid red; } .cat{ height: 50px; width: 200px; border: 1px solid blue; } .black{ background-color: #000000; } .white{ background-color: #ffffff; }

Each HTML element can be defined by multiple CSS classes... but they can only have one ID:

<div id="spike" class="black dog"></div> <div id="fluffy" class="white cat"></div> <div id="bowser" class="black cat"></div>

This will render three boxes: #spike will be a short box with a black background and red border, #fluffy will be a longer box that is white with a blue border, and #bowser will be a black with a blue border. You can see from this example how HTML elements can share classes.

Below you will find an example of what chapters one and two look like combined into one file. Ideally you would want to include the CSS separately your files by using link tags within the head, but for the sake of this very basic example... it helps you understand where the information belongs.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Website Title</title> <style> #spike{ display: block; height: 50px; width: 100px; } #fluffy{ display: block; } .dog{ height: 50px; width: 200px; border: 1px solid red; } .cat{ height: 50px; width: 200px; border: 1px solid blue; } .black{ background-color: #000000; } .white{ background-color: #ffffff; } </style> </head> <body> <div id="spike" class="black dog"></div> <div id="fluffy" class="white cat"></div> <div id="bowser" class="black cat"></div> </body> </html>

So, CSS is used to give elements of a website some style. If you didn’t use any CSS, the styles would default to the browser’s native styles... basic black serif fonts with blue underlined links.

CSS has state selectors that are used to modify the class of an element that is being interacted with...

a{ text-decoration:none; /* turn off the default underline with text-decoration */ color: red; } a:hover{ /* :hover is the mouse-over state of the element */ text-decoration:underline; color: green; } a:active{ /* :active is the mouse-down state of the element */ color: blue; } a:visited{ /* :visited is the state of a link that exists in the user's history */ color: purple; }

This will make every link on your page red by default, blue when moused-over, and yellow while being clicked. These state selectors can be used on ANY html element.

You can combine rules for multiple classes by using commas:

.cat, .dog, .snake{ border: 1px solid red; }

... and you can even be more specific:

ul.groceryList{ background-color: black; color: blue; } li.purchased{ background-color: green; color: white; }

These rules make an unordered list with a black background a blue text. Notice how ther is no space between the element and the class name. This is a way of saying "only these specific elements that have a class of.." -- so any of the li tags with a class of "purchased" will have a green background and white text!

<ul class="groceryList"> <li>bread</li> <li>milk</li> <li class="purchased">butter</li> <li>cheese</li> </ul>

The "Box Model"

All block-level elements follow the "box model" -- below is an example:

.box{ width: 250px; height: 150px; padding: 25px; margin: 25px; background: rgba(0,0,0,.25); border: 25px solid rgba(0,0,0,.25); }
:before
content
:after
padding
border
margin

Pseudo Elements

All container elements have the ability to expand into 3 elements. These extra two elements do not appear in the DOM, and as such, are not search friendly and should only be used for presentational purposes (icons, css triangles, etc.).

Pseudos come in two flavors: :before and :after. They actually live within the container that they belong to, so they can be positioned relative to the parent if that parent is not position: static;.

Animations and Transitions

CSS3 animations come in two flavors: transitioned, and keyframed.

CSS transitions are mainly used for defining how an element will transition between states. One example is a link switching colors when your mouse is over it. A CSS transition can be written to make the fade smooth. They are written like this:
transition: property length easemode

a{ color: red; transiton: color 250ms ease; } a:hover{ color:blue; }

Transitions can be super powerful when combined with the transition-delay property.

Specificity

The nature of CSS is that classes, and therefore properties, stack on each other in a cascading manner. Styles are applied in order that they are listed in the stylesheet... so they can be overwritten by rules that appear later in the file!

a{ color: red; font-size:25px; } a{ color: purple; font-size: 12px; }

All of the links on this page would be purple and 12px tall.

Rules with a higher specificity are considered more important than rules with a lower specificity, regardless of their position in the stylesheet. Some of the things that will raise specificity (besides adding !important to the rule) would be like adding a parent or two. For example:

ul li a{ color: red; font-size:25px; } a{ color: purple; font-size: 12px; }

On this page, all of the links would be purple and 12px EXCEPT the ones that were inside li tags. Use this to your advantage... and if you ever find yourself adding !important to a rule, reconsider the specificity!

Adaptive Design and Responsive Techniques

Your website will be accessed by so many different devices these days that it is almost hard to keep up. Laptops, phones, tablets and fablets... will your website flow well on one of Apple's Retina screens? Well, it can!

Media queries give you the ability to overwrite different CSS style options based on the width of your user’s screen. Gone are the days of redirecting users to separate URLs based on their device!

Here is an example of a CSS3 media query that could be used to hide a hero banner when the end user's screen is less than 600px wide...

.hero_banner{ width: 600px; height: 200px; background: red; } @media (max-width: 600px) { .hero_banner { display: none; } }

This media query basically says "at a screen width of less than 600px, overwrite these rules:" -- and proceeds to hide the .hero_banner class. demo

You can set up some very specific media queries in your quest to support whatever devices you wish. Just be sure to define the viewport settings (within the head) or your site will render the same in every device:

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

JavaScript

You are the magician.

Abracadizzle

JavaScript (JS) is what really makes all of the magic happen on a website. You can use JS to do things like:

DOM Tree

You could think of the Document Object Model (DOM) as a tree where each branch literally represents the layout of your code. The html tag the root of the treeand then it splits into into the head and body tags, and each have multiple branches. These branches are called “parents” and “children” in reference to the DOM.

DOM elements can be retrieved, replaced, moved, animated, hidden or shown, and modified by using JavaScript!

Event Bubbling

Interaction events can be extended to provide more functionality in a page.

When a mouse click event is triggered on a page, it will originate in the container that was clicked and propogate up through the DOM tree to the body. This click event can be intercepted at any point in it's DOM traversal and cancelled (e.g., in the event of a link click where you don't want any action happening) or used to perform other functions.

DO NOT USE EVENT TRIGGERS TO BREAK DEFAULT INTERACTIONS! There are many frustrating examples around the internet that show developer apathy in regards to natural interactions. Don't hijack the spacebar (used for scrolling in chunks) or the arrow keys (scrolling) unless you are building an app and the interactions are intuitive.

'Vanilla' JavaScript

JavaScript was created in 1995. It was used for gimmicky reasons for many years, and never really taken seriously until the early 2000s.

JavaScript runs on the end-user's browser when a page is loaded that uses it. You can also demo your scripts in your browser's JavaScript console.

Libraries - jQuery

There are many common functions one uses while writing JavaScript such as accessing an element’s attributes, altering classes, injecting content, etc. There are easily hundreds of ways to accomplish these common tasks. Instead of rewriting these functions every time you need to start a new website, they have been collected and refined into a library for use by anyone and everyone! This keeps all of the programmers on the same page, using the same functions, and speaking the same language. jQuery is a shorthand version of JavaScript that is only usable if you include the jQuery library.

jQuery has many built in triggers that you can use to script events or fire functions when the end user interacts with your DOM elements:

var windowWidth; var windowHeight; function getWindowSize(){ windowWidth = $(window).width(); windowHeight = $(window).height(); console.log("Window is "+windowWidth+" by "+windowHeight+"."); } $(window).resize(getWindowSize); /* updates variables when the window is resized */ $(document).ready( function () { getWindowSize(); alert(“Window is “+windowWidth+”px by “+windowHeight+”px”); });

Here is an example of the same operation performed with vanilla JavaScript versus jQuery:

JavaScript

var dataValue = document.getElementById('linkHome').getAttribute('data'); console.log(dataValue);

jQuery

var dataValue = $('#linkHome').attr('data'); console.log(dataValue);

Arrays

An array is a collection of variables within one variable. Usually, arrays are used to hold a lot of the same type of value that can be accessed by calling its position in the array.

var someArray = new Array(); someArray.push(500); // push value into array console.log(someArray[0]); // prints 500 // or var anotherArray = [“Jack”, “Jill”, “John”]; console.log(anotherArray[2]); // prints “John”

Constructed Object

You can think of an object like an empty bookshelf. Each shelf can contain any kind of variable, ranging from integers, strings, to booleans and even arrays, functions, and other Objects! Each of these “shelves” is given a name, and can be called upon and used. A constructed object is one that is created and can be instantiated multiple times:

function Book(t,a,p){ this.title = t; this.author = a; this.pages = p; } var artOfWar = new Book(“The Art of War”, “Sun Tzu”, 197); console.log(artOfWar.author);

Object Literal

An object literal is a “singleton”... it cannot be instantiated multiple times, but usually only exists to provide a single function, or store a set of variables:

var aCar = { name: "Tesla", height: 40, weight: 2000, forward: function () { console.log("Move car forward..."); } }; console.log(aCar.name); aCar.forward();

Cool, right?

Accessibility

making websites for everyone...

Ideally, every website on the internet would be designed with the impaired in mind; in reality most are not. Google even offers the ability to search their site by voice! Others have been experimenting with this technology as well.

Colorblindness

Almost one in five males are colorblind, and one in 10 females -- this is a very important thing to consider when you are choosing the palette of your sites.

It’s All About Shades

To make this easier to understand, think about all the shades of all the colors you’ve ever seen. For instance, when you think of the color “green,” think about how many completely different color swatches could match your definition of green. Bright, dark, muted, watercolor, neon; on and on. This includes the slightest variations where one green might contain just a tiny bit more red or blue light than the another green.

Now imagine you counted all of these different shades of green that your eyes are capable of perceiving and they equaled, say 1 million (completely arbitrary number). Now give the same task to a colorblind person and they might come up with 500,000 or less.

So you see, it’s not that colorblind people (in most cases) are incapable or perceiving “green,” instead they merely distinguish fewer shades of green than you do. So where you see three similar shades of green, a colorblind user might only see one shade of green.

To make it even more complicated, similar shades from different colors often run together and make it difficult to determine precisely what color something actually is.

Joshua Johnson - DesignShack

Touch Screens

A large percentage of the devices that will be accessing your website will be touch capable. There are important things to consider, like having touch controls for keyboard events, buttons large enough for fingers, and if you want to support drag/slide controls.

Screen readers

It becomes more important with every new iteration of HTML to know what each element was actually created for and how they react in different situations. For instance, text in an abbr element is handled differently than text in an acronym element by a screen reader: "NASA" vs "N.A.S.A."

Semantics is the art of giving logic (and therefore meaning) to blocks of text. You may think your code has plenty of detail... but could a computer interpret the meaning?

Using the correct tags in the correct places is how you generate semantically correct code. Only use the DIV tag when there is not a better HTML to describe the element.

Accessibility Tips

Which leads us to...

SEO

there are spiders all over your <body>!

Search engine optimization is 90% planning, 10% execution. In short, search engine friendliness is based on the semantics used in your code and the relevence of the content within.

In this Chapter, we will focus on Google because everyone knows Bing! gets their results from Google, and Yahoo! isn’t good for anything anymore Google leads the way in search results, technology, and web developer tools.

Since February 2011, Google has been updating their indexing algorithm almost monthly. These updates have been referred to as “Panda” and have been announced on each occasion but Google has discontinued announcements as of March 2012.

Panda was designed to remove sites from Google’s index that are “gaming” the system, or doing things like spamming their links around the web in irrelevant places just to get more incoming reference traffic to their site. This is called “black hat” seo and is frowned upon by real web developers. There are people that make a living as SEO consultants.

These days, Google's indexing is both automatic and manual. Things can be tagged as suspect of using shady techniques and then a team of real people visit the page and check out the offending code. Shit is real, son!

If your project is thought out, well-planned, and properly executed you should never have a problem with your SEO. Here’s a short list of ethical practices that you can do to help your site rank well with search engines:

Short and sweet: Be ethical; use solid content wrapped in semantic tags and link to stuff when you mention it. You can also use tools like Google’s Web Developer Console to expedite site crawls, check for errors, and upload your sitemaps so the bots know where to look! It may take a few hours, but they will have you listed when you search for your title rather quickly. "Seasoned" content is better than content that is updated too often.

Extra Stuff

because it is worth thinking about

Organization

There are many reasons why you should keep your code and files organized neatly. If another developer is ever brought on to work with (or in place of) you, they need to be able to read the source. On the other hand, you may have to return to a project that you created years ago to update it, as you will often, it is nice to feel like you are in a familiar place.

Below is an example of a clean and basic front-end folder hierarchy:

project root
css/
  • style.css
  • grid.css
  • effects.css
images/
  • logo.png
js/
  • jquery.js
  • ready.js
.htaccess
index.html

Images, script files, and stylesheets have their own folder. Ideally, you will want to keep this pattern all of the way down to the file level to maintain manageability.

Getting Paid

One of the toughest things to do as a developer is deal with people who are NOT developers. It can be even worse trying to manage the expectations of a client. Be sure to check out this epic speech given by Mike Monteiro called Fuck you, pay me. You will inevitably run into a client that will not want to pay you. You need to know how to protect yourself going into the situation. Contracts are their wording are important. Be careful about quoting projects when you are unsure of the scope. 99% of the time the client will not actually know what they want... beware of scope creep.