About the Author:

How to Make Circular/Curved Text with JavaScript

September 28th, 2016

Creating circular text, or text on an curved path, in webpages may seem like somewhat of a intimidating task. There isn’t really a straightforward way to achieve it with standard HTML and CSS. There is a JavaScript plugin or two out there with some pretty decent results, but using plugins means extra dependency and load time associated tacked on to your project. So… what can you do? With a little bit of plain old vanilla JavaScript and standard CSS, it’s actually not that difficult to create curved text of your own! In this article, I’ll show you how to create circular/curved text that relies on as little as 15 lines of JavaScript. The result is functional and reusable so that you can apply as much circular text to your projects as you would like! You won’t need any special libraries or plugins of any sort; just good old fashioned HTML, CSS, and JavaScript. I’ll provide examples as we go, and I’ll provide items for consideration along the way. Circle the wagons; let’s get started!


Circular Text: The HTML

We’ll start by setting up the HTML, which is pretty much as simple as it gets. You’ll want a container for the circular text (although not 100% necessary) as well as a target element in which you’ll insert your circular text. Here’s how I’ve got it set up:

See the Pen ALoKJJ by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The CSS

Next we’ll add a some CSS to get things set up. None of the following CSS is actually necessary, and it can be adjusted as needed. For the purposes of this tutorial, I chose a purely arbitrary blackish background with whitish text; I also chose to center the target element (the div with class=circTxt), but you can choose to position the containers and target elements however you please! Here’s how I have the CSS:

See the Pen NRvNEv by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The JavaScript

Next comes the magic, the JavaScript. Things get a bit more complex here, but the overall logic isn’t really all that difficult. To give a broad overview before actually looking at the code, here’s what we’ll want to accomplish:

  1. Create a reusable function named circularText that takes 3 arguments: 1) the text to be written in circular fashion, 2) the radius of the circle on which the text will lie, and 3) the DOM index of the target class=circTxt element
  2. Split the text in to an array and get it’s length (i.e., the number of characters it contains)
  3. Divide the total degrees in a circle (i.e., 360 deg) by the length/number of characters in the text to determine spacing
  4. Specify the origin, or starting point, for the circular text (for simplicity’s sake, I’m going to hardcode 0 degrees)
  5. Create a loop (here using Array’s forEach method) that inserts the text around the perimeter of a circle using the defined radius and updating the origin/start value as it goes
  6. Call the function to create the circular/arced text!

Got all that? Believe me, it’s really not that complicated; less than 15 lines if you please. Here’s what the code looks like:

See the Pen rrzZoK by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

NOTE: I am do use ES6 syntax there (the arrow function and the template literal), but the code can easily be refactored to comply with more traditional syntax.


Well… there you have it… circular text with plain old HTML, CSS, and JavaScript!

Some things to consider are the need for adjusting the passed radius value based on how many characters are in your text. Generally speaking, the more characters you have in your text, the larger the radius you’ll need to use (however, you can create some neat effects by using a radius that might initially appear to be too small). Also note that you can created arced or curved text without going around a full circle by being purposeful about using spaces in your text.

See the Pen kkobjp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

The arc effect can also be achieved by modifying the origin value used in the code (i,e., starting somewhere other than at the top of the circle). Regarding modifications to the CSS, the code could be changed to target elements with specified ids or tag names; you could use the document object’s querySelector method to achieve precision targeting as well. Additionally, you can modify both the circTxt containers (positioning them wherever you like on the page, giving them height and width, etc.) and the circular text within.

See the Pen Circular Text Generator by Chase Allen (@ccallen001) on CodePen.

I encourage you to go wild, get creative with it, circle back and have some fun! :)

About the Author:

CSS: Simple Sticky Footer

September 22nd, 2016

The sticky footer…

The oh-so-sought-after expanse at the bottom of the page that contains contact information, site navigation, a call to action, or whatever else you might want to chuck in there. It’s the element that knows its place in the world (wide web) and embraces it by staying in it’s place. A well executed sticky footer encourages your site visitors to further engage; it encourages your site’s visitors to interact with your page’s content in a familiar and enjoyable fashion.

Fortunately, creating a sticky footer isn’t really all that difficult. In the following tutorial, I’ll show you a couple quick and simple methods for making a slick looking sticky footer, one that plays well with the modern web… one that deftly displays valuable information across varying screens and multiple devices. Best of all, I’ll show you how to create your footer in a relatively simple fashion in which you won’t need to mess with unnecessary libraries, fancy plugins, or less than desirable “hacks.”

Step 1: Behavior and Positioning

First things first, you’ll want to decide how your sticky footer will be displayed; i.e., how it will behave on your page. For the purposes of this tutorial, I’ll assume there are generally two choices for you with respect to your footer’s behavior: 1) your footer can stick to the bottom of the body of your page, changing position according to your page’s body’s height, or 2) it can stick to the bottom of your browser’s window, effectively rendering the footer as an omnipresent entity on the page. Both are relatively easy to achieve and have specific advantages and disadvantages when compared to the other. Ultimately the choice is  yours.

Here’s how to stick the footer to the bottom of the body:

See the Pen EgvKKR by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note: 1) the body has relative positioning 2) the sticky footer has absolute positioning and a defined width 3) the bottom property for the sticky footer is set to 0.

Here’s how to stick the footer to the bottom of your browser window:

See the Pen QKrNEd by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note: 1) the body still has relative positioning 2) the sticky footer now has fixed positioning and a defined width 3) the bottom property for the sticky footer is still set to 0.

With both approaches, using relative units (i.e., percentage or viewport units) will allow for your footer to respond to various screen widths.

Like I said, pretty simple It really doesn’t take much more than that to create a pure CSS, simple sticky footer. But of course, we want more… Let’s take a look at getting some content in there.

Step 2: Add Some Content

So you’ve got your footer… stuck to the bottom of your page or your browser’s window… Let’s flesh it out some more with some useful information. For the purposes of this demo, I’m going to go with a mock site navigation block, a contact information block, and a call to action button.

Here’s the populated sticky footer:

See the Pen pEAyEw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note here: 1) the sticky footer’s text-align property is set to center 2) div elements within the footer with display:inline-block are being used as containers 3) relative units and min- and max-widths are being used.

Aligning the text to the center and giving the containers a display of inline-block just creates a nice alignment for the content. The min and max widths further control spacing and wrap behavior; the relative units assist here as well. Next, let’s look at classing things up a bit.

Step 3: Add Some Effects

Things are looking good! You’ve got a well populated sticky footer with information balanced throughout. It’s easy to read and easy to access and it looks good across multiple browsers and multiple devices. Great! But let’s say we really want to draw in some visitors. What can we do? We can add some fancy schmancy effects to our footer, that’s what we can do! :) Let’s take a look at a few relatively simple effects that you can add to your footer in order to really draw attention to it.

If you want a relatively modest approach, there are shadow effects.

Shadow:

See the Pen bwApBw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

A more modern approach may be to let the background shine through.

Transparency:

See the Pen RGkaKb by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

How about some interactivity?

Hover Transition:

See the Pen Xjadpq by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Let’s really get their attention!

Animation:

See the Pen ozZxkO by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

And just to take it back to a world wide web of yesteryear…

Animated Background:

See the Pen jrLqmw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

With effects, your own creativity is the limit!

Conclusion

In this tutorial, I showed you how to make a relatively simple sticky footer without needing to rely on any external libraries or unsavory methods. I showed you how to stick your footer to the bottom of your page or to the bottom or your browser’s window. I showed you how to get basic responsiveness going and how to fill your footer with content. We then looked at some neat effects that hopefully gave you some inspiration of your own. That concludes this tutorial on creating a simple sticky footer. Thanks for sticking with it!

About the Author:

Interactive Mapping with Python, GeoJSON, and JavaScript

August 19th, 2016

Interactive maps are a powerful tool for data visualization and user interfaces. Providing rich content based on geographic location is the cornerstone of many apps such as Yelp,  Zillow, and Road Trippers. In this post we are going to create an interactive map of campgrounds using the Google Maps API, JavaScript, and Python.

The codepen below shows what we’ll be building:

See the Pen Finished Map by Sev (@sevleonard) on CodePen.


What We Will Achieve Here

  1. Build a Google map with JavaScript.
  2. Convert geographic campground data from a CSV to GeoJSON so Google Maps can read it.
  3. Load the GeoJSON into Google Maps and set up click events and interactivity.
  4. Go camping at Crater Lake (optional).

Designing with Maps

A good map-based application, or really, any good application, begins with thinking about what functionality you want to provide and how users will interact with it. Here are some questions to consider while you’re specing things out.

  1. What geographic region do you want to map?
  2. What kind of map makes the most sense for your application? Topographic, traffic, congressional districts?
  3. What information do you have to add to the map?
  4. How will end-users interact with the map?

For this example, we want to build a map to help people find a place to camp near Crater Lake, Oregon. Crater Lake is a popular tourist destination and the deepest lake in the United States, though folks from Lake Tahoe may disagree. Disagreements aside, we know we want a map of the Crater Lake area and we want to display information about campgrounds.

Regarding the type of map to use, let’s think about what would be important to a person looking for a place to camp. Certainly a camper would want to know how they can get to Crater Lake from a campground, so we definitely should pick a map that shows roads. Perhaps we read a study of outdoor recreation and found that most campers prefer to camp in shaded areas. With satellite imagery campers could identify shaded campgrounds by looking at the tree cover, so that seems like a good bit of information to include in our map.

Using information from the National Forest Service, we have a dataset of eleven campgrounds closest to Crater Lake. Each data point includes the campground name and location with some additional features on campground amenities: showers and toilet type – vault or flush. We’ll display the data using map markers for each campground, displaying the amenities if the user clicks the marker to learn more, like this:

Now that we have an initial design, let’s get into the details of making it happen.

Setting up a map element

We’ll setup our campground finder as a web app that runs in the browser. We need a reference to the Google Maps API and a div element where the map will be displayed.

<script src="https://maps.googleapis.com/maps/api/js"></script>

<div id="map"></div>

For this example we are not specifying an API key, so you will see a warning “NoApiKeys” when running the code in codepen. If you are using the Google Maps API for your web application you should get an API key and note the usage limits. As long as you stay under 1,000 map loads / hr you should be good with the free plan.

One last thing before we move on – we need to set the size of the map div. If you forget to do this, you’ll find yourself staring at a blank page. Not super helpful for finding a place to camp.

#map {

  width: 600px;

  height: 500px;

}

Customizing the map

At this point our app isn’t very exciting. Just a blank HTML page. Now we’ll setup and display the map, recalling our design specs.

Map types – We decided we wanted to show roads and satellite images for our campground map. Conveniently this sort of map is one of the basic map types, hybrid.

Zoom Level – The initial level of detail is determined by setting the zoom level. A zoom level of 10 will give us enough detail to show all the campgrounds near Crater Lakes and the major roadways.

Center – as you would likely expect, this is the latitude, longitude where you’d like to center the map. Our map is centered at Crater Lake.

We’ll encapsulate these parameters in the map_options object:

map_options = {

zoom: 10,

mapTypeId: google.maps.MapTypeId.HYBRID,

center: {lat: 42.9446, lng: -122.1090}

}

Initializing the Map

Using the Map constructor, we pass the map_options and the map div to create a new object “map”.  We will refer to the map object later when we are ready to add the campgrounds.

map_document = document.getElementById('map')

map = new google.maps.Map(map_document,map_options);

Let’s set the map to draw when the page is loaded. To do this, we’ll add a call to addDomListener. The initMap function containing our map setup code will be called when the window is loaded.

function initMap() {

   map_options = {

     zoom: 10,

     mapTypeId: google.maps.MapTypeId.HYBRID,

     center: {lat: 42.9446, lng: -122.1090}

   }

   

   map_document = document.getElementById('map')

   map = new google.maps.Map(map_document,map_options);

}

google.maps.event.addDomListener(window, 'load', initMap);

Alright! We are now all set to load a map. If you run the codepen you should see this map of Crater Lake and the surrounding area

See the Pen Finished Map by Sev (@sevleonard) on CodePen.

Getting data for our map

Now that we have a map, lets get some data to add to it.  Google Maps can read data in a variety of different formats, including GeoJSON, which we will be using in this example.  All we need now is a bit of Python code to convert the data to GeoJson. The code in the next section uses Python 3.4.3 and version 0.18.1 of the pandas library. You can follow along using the Jupyter notebook here

Data cleaning

When working with data it’s important to begin by reading it! We need to convert our data from a CSV format to the GeoJSON format that Google Maps can read. Using the Python pandas library, we can read data into a tabular structure called a DataFrame. We can use this object to observe, analyze and manipulate the data. The campground data is in a CSV format, we can use pandas read_csv to read this into a DataFrame.

# import the modules we need to convert the CSV data to GeoJSON
import pandas as pd

import numpy as np

from pandas import json

cg_data = pd.read_csv('campgrounds.csv')

# inspect the data, take a look at its shape (rows, columns) and the first

# few rows of data

cg_data.shape

>> (11, 6)

cg_data.head()

Each row represents a campground, with its name denoted by the facilityname field, a string. The latitude and longitude in numeric format are next, followed by the amenities – flush toilets, showers, and vault toilets. The amenities fields have three possible values: 0,1, and ‘\N’.  0 denotes False, 1 is True, and ‘\N’ indicates the data is not available.

We want to transform this data into valid GeoJSON, for example:

Example GeoJSON:

{

"type": "Feature",

"properties": {

"title":"Ainsworth State Park",

"description": "Flush toilet, shower"

}

"geometry": {

"type": "Point",

"coordinates":[-122.048974,45.59844]

}

}

We’ll use the facility name for the ‘title’ field, and create a string of the amenities for the ‘description’ field. A few lines of Python to change some column names and replace amenity field values should do the trick:

cg_data_clean = cg_data

# replace the amenity values with the appropriate strings

cg_data_clean = cg_data_clean.replace({'flush': {'1':'Flush toilet', '0':'', '\N':''}})

cg_data_clean = cg_data_clean.replace({'shower': {'1':'Shower', '0':'', '\N':''}})

cg_data_clean = cg_data_clean.replace({'vault': {'1':'Vault toilet', '0':'', '\N':''}})

# rename columns to be consistent with the GeoJSON field names

cg_data_clean = cg_data_clean.rename(columns={'facilityname': 'title',

                                             'facilitylatitude':'latitude',

                                             'facilitylongitude':'longitude'})

We can concatenate the amenity fields into a single ‘description’ field using the .join() function inside an apply. The apply function enables you to perform operations over rows (axis=0) or columns (axis=1) of a DataFrame. This leaves us with some extraneous leading and trailing commas for this data set, so we also have a helper function, clean_description, to strip leading and trailing commas.

# create description field

cg_data_clean['description'] = cg_data_clean[['flush','shower','vault']].apply(lambda x: ', '.join(x), axis=1)

# function to clean the leading / ending commas from the description. This won’t remove commas in between fields, though!

def clean_description(description):

   description = description.strip()

   while((description.startswith(',') or description.endswith(',')) and len(description) > -1):

       if description.endswith(',') :

           description = description[0:len(description)-1]

       if description.startswith(',') :

           description = description[1:len(description)]   

       description = description.strip()

   return description

# apply the clean_description function to all rows

cg_data_clean['description'] = cg_data_clean.description.apply(lambda x: clean_description(x))

We no longer need the individual amenity columns, having concatenated them into the description column, so we can drop those moving forward. We’re ready to convert the DataFrame to GeoJSON, which we will again call on our new friend apply to help with. Thanks to Geoff Boeing and his post on Exporting Python Data to GeoJSON for some insight here.

Recalling our GeoJSON example above, each campground will be a feature, part of a FeatureCollection object. The approach here is to create a collection object and add features to it as they are processed by the feature_from_row method.

# create the feature collection

collection = {'type':'FeatureCollection', 'features':[]}

# function to create a feature from each row and add it to the collection

def feature_from_row(title, latitude, longitude, description):

   feature = { 'type': 'Feature',

              'properties': { 'title': '', 'description': ''},

              'geometry': { 'type': 'Point', 'coordinates': []}

              }

   feature['geometry']['coordinates'] = [longitude, latitude]

   feature['properties']['title'] = title

   feature['properties']['description'] = description

   collection['features'].append(feature)

   return feature
# apply the feature_from_row function to populate the feature collection geojson_series = geojson_df.apply(lambda x: feature_from_row(x['title'],x['latitude'],x['longitude'],x['description']),

axis=1)

Looking at the ‘collection’ object we can see how the DataFrame was converted to GeoJSON. Here are the first two features in our FeatureCollection:

Using pandas json module we can write the collection out to a geojson file with the correct formatting. We’ll reference this file to pull in the campground data for the map.

with open('collection.geojson', 'w') as outfile:
   json.dump(collection, outfile)

Adding GeoJSON data to the map

We have our base map and our campground GeoJSON. We just need a little more JavaScript to pull all of it together. Google Maps has a super convenient loadGeoJson method that we can use to get our points onto the map right away:

geojson_url = 'https://raw.githubusercontent.com/gizm00/blog_code/master/appendto/python_maps/collection.geojson'

map.data.loadGeoJson(geojson_url, null, loadMarkers)

Running this in codepen, you should see markers added to the map. Those are the campgrounds! Hover over a campground to see its name given in the ‘title’ field.

The loadMarkers parameter in the loadGeoJson call above is a callback function we will use to add information to the markers. Once the GeoJson is loaded, loadMarkers gets called and the marker objects and pop up windows (info windows) are created. The InfoWindow content field is a string that accepts HTML tags, so you can format and style the pop up as you like. This last codepen includes the code for adding the infoWindow to the markers.

function loadMarkers() {
 console.log('creating markers')
 var infoWindow = new google.maps.InfoWindow()
 map.data.forEach(function(feature) {
   
   // geojson format is [longitude, latitude] but google maps marker position attribute
   // expects [latitude, longitude]
   var latitude = feature.getGeometry().get().lat()
   var longitude = feature.getGeometry().get().lng()
   var titleText = feature.getProperty('title')
   var descriptionText = feature.getProperty('description')

   var marker = new google.maps.Marker({
     position: {lat: latitude, lng:longitude},
     title: titleText,
     map: map
    });
   
   var markerInfo = "<div><h3>" + titleText + "</h3>Amenities: " + descriptionText + "</div>"
   // by default the infoWindow for each marker will stay open unless manually closed

   // using setContent and opening the window whenever a marker is clicked will

   // cause the prior infoWindow to close
   marker.addListener('click', function() {
         infoWindow.close()
         infoWindow.setContent(markerInfo)
         infoWindow.open(map, marker)
       });
   markers.push(marker)
 });
}

We’re all done! Try it out and see which campground you’d prefer. One last note, we’re keeping an array of the current markers for later use when it will be needed for functions like filtering.

Summary

Congratulations! You now know how to clean and format raw data and use it to create an interactive map. Maybe you can think of some additional information you’d like to add to the map like current weather or cell phone coverage. You can follow the same procedures we used for cleaning the campground data to other information sources, and adding these features to the ‘description’ GeoJSON field to easily include it on your map. Happy mapping!

 

About the Author:

The Cost of Implementing Responsive Web Design Later

September 9th, 2014

I’ve done more than a few responsive website implementations and there are two ways that it can happen. A site can be coded responsively or you can be tasked with doing a retrofit to make a fixed-width site responsive.

Is it better to get a desktop site out quicker and then work on making it responsive as a “phase 2”? Having done both I can say that it’s a good idea to start with responsive in mind. Doing a retrofit is usually a frustrating and expensive process. Let’s look at how.

Ramping up

The first cost you’re going to encounter when implementing responsive web design (RWD) later is getting familiar with the codebase. This is true for both new developers and the project’s original developers. When you revisit past code it takes some time to get back “into the groove”.

In addition to that, you’re thinking a lot differently than you would on a mobile-first project. Normally you think of how you’re going to build or how you’re going to add on to or expand on what’s there. Now, once you’ve wrapped your head around what’s going on, you have to think in terms of fundamentally breaking down and changing how the code works. It’s a major refactor.

Style gutting

It’s easy to make the connection of time saved in your head if you’ve already got all the styles for the desktop or largest version of your site. However, we run into hidden costs when it turns out that we have to disassemble all of those styles and reassemble them in the correct order. The advantage is similar to having all of your puzzle pieces in the same box but not pieced together.

Disassembly is needed to make sure the styles are mobile first. Otherwise, you’re going to have to undo a lot of styles for the mobile view. (Ask someone who’s done it how fun that is!) What this proces looks like is slicing out specific rules and relocating them in media queries. It’s a tedious task.

Not just styles

When you think of what makes a site responsive you probably think of the CSS. It is what makes a site look the way it does and CSS is the most important part of making a site responsive, but it’s not the only thing. Forgetting other aspects can really break the user experience.

Markup requirements

Out of HTML, CSS, and JavaScript, my brain automatically ranks HTML as being the easiest and most straightforward. You put the words and pictures you want to be on the page into the HTML document and you wrap them in tags that describe the kind of content that it is. While that is true, you also have to account for structure and layout when you write HMTL.

Once you start thinking of how the CSS is going to affect the markup, it changes how you might write it. This is especially true when creating responsively. You have to consider that the module you’re structuring may appear four different ways and on three different parts of the page. Here’s a small example.

<section class="main-content">
    <!-- Some Content -->
</section>

<section class="secondary-content">
    <!-- Other Content-->
</section>

<aside class="side-module">
    <!-- tangential content -->
</aside>

Let’s look at this as if this as if it’s the original markup to a site we’re retroactively making responsive. From the markup it looks like `main-content` and `secondary-content` will be the focus of the page and `side-module` will float to the side – let’s assume the CSS reflects that.

Now that it’s time to make this responsive, the new mocks show that the smallest version the site becomes single-column and `side-module` will sit between `main-content` and `secondary-content`.

While the solution here is simple, real-world pages are not usually this simple and added complexity will bring more complex problems. If we had approached this mobile first, it wouldn’t have been a problem. It would have just been a requirement that we factor into our original structure.

Retrofitting a site will introduce you to lots of similar issues. (And if you have to do a retrofit where you’re not allowed to touch the markup, all I can say is I’ve been there and I am very sorry.)

Responsive JavaScript

Responsive web design changes the way you think about web pages. Since you’re trying to accommodate as many devices as you reasonably can, you have to consider how people interact with your site. You also have to consider (please forgive the pedantry of this sentence) how your site interacts with them.

Sometimes there are behaviors that only make sense at the desktop level and sometimes it’s the other way around. Your scripts need to be aware of the context and know when to fire and when to not. Having this built in from the beginning is handy. Building it in later is really just refactoring, which is very normal for writing code, but doing something right the first time is always preferred.

To give a recent example of this, while working with Zumba for a responsive redesign of their site, we had a module that needed to stick to the bottom of the window until you scrolled down and it fell into position. We would not want that on mobile since real estate is limited, so we stopped it from happening on mobile widths. Using a tool like mediaCheck makes this relatively simple, but the hidden cost on a retrofit is that all of your JavaScript has to be audited for similar problems.

Testing – All over again

Remember all those hours of testing, and bug fixes, and more testing? Get ready to do it all over again. You’ve just introduced new code into all three layers of your site: HTML, CSS, and JavaScript. It’s bound to cause problems that must be fixed before launch.

Are you supporting IE8? As you may know, it doesn’t do media queries. IE8 users will either get just mobile styles or you’ll need a way to serve the styles enclosed in media queries. There are several solutions you can use for this, but it’s better to do them from the ground up.

It’s more than it seems

As stated earlier, what makes a site responsive is not just style. So doing it after the fact means you are probably altering a lot of what you started out with. Did you really just update your codebase or is it more likely that you made a new site? The cost will probably look more like the latter.

Having done both ground-up responsive sites and retrofits, I can say coming to a clean slate is much more comfortable.

About the Author:

Solving the Holy Grail Layout

March 18th, 2014

Searching for the elusive Holy Grail of CSS layouts has lead to many clever solutions, but never has there been a single solution that doesn’t involve hacks or drawbacks. Tables, divs with table-property displays, and absolutely positioned divs are some of the ways we’ve accomplished the Holy Grail layout in the past. With the introduction of Flexbox though, we can end our search for the Holy Grail of web layouts. With the power of CSS3, the once highly sought after solution has been found.

(more…)

About the Author:

Pure CSS Triangles Explained

March 27th, 2013

Over the past couple years plenty of great articles around the web have extolled the virtues of using pure CSS shapes for everything from subtle decorative elements, to complex interface icons. The primary benefits touted for constructing such visual elements with CSS alone include:
(more…)

About the Author:

Enterprise Strategies for Adopting HTML5 Part 1: Simplified Syntax & Semantic Elements

August 18th, 2010

<div class=”note”>This is the first post of a multi-part series covering strategies that you might use to adopt HTML5 in your current or future corporate websites.</p></div>

<h2>Introduction</h2>

HTML5 has many features which you’ve likely heard about or seen in various blog posts. With all of the publicity HTML5 has begun to hold weight as a marketing term and businesses are paying attention. In the near future we’ll see businesses want to leverage HTML5 to send a message that they are innovative and competitive.

Unfortunately many of the HTML5 features are not fully implemented in the newest versions of modern browsers. Older browsers lack any HTML5 support. This leaves us with a key question: “To what extent can I use HTML5 inside my enterprise application?”

In this blog series we will deliver a strategy you can use to start adopting HTML5 <em>today</em>. We’ll break down the strategy into the following posts:

<ul>
<li>Part 1: Simplified Syntax &amp; Semantic Elements</li>
<li>Part 2: Form Enhancements</li>
<li>Part 3: Local &amp; Session Storage:</li>
</ul>

<p style=”margin: 0px 15px 15px 50px; font-style: italic;”>Client storage is no longer part of the HTML5 specification. Nevertheless we’ve decided to cover client storage as it is still popular as a topic in HTML5 discussions and is implemented in many of the modern browsers.

<ul>
<li>Part 4: Video &amp; Audio Elements</li>
</ul>

<!–more–>

<h2>Simplified Syntax</h2>

<div class=”note”>All of the techniques that are shown in this section (DOCTYPE, Encoding, Script, Style, and Link) work in current and past browsers. No additional work is necessary to provide this support. We recommend you adopt these changes now and only use the old syntax if you have a specific reason to do so.</p>

</div>

<h3>Simplified DOCTYPE</h3>

Selecting a DOCTYPE is a necessary part of building a web page. There are many to choose from depending on how you compose your markup. Here is a list of several common DOCTYPEs you may have seen.

<h4>Old Way</h4>

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
&quot;https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;https://www.w3.org/TR/html4/loose.dtd&quot;&gt;

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;
&quot;https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Frameset//EN&quot;
&quot;https://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd&quot;&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot;
&quot;https://www.w3.org/TR/html4/strict.dtd&quot;&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Frameset//EN&quot;
&quot;https://www.w3.org/TR/html4/frameset.dtd&quot;&gt;

Some developers and designers know what all of those DOCTYPEs mean, but I would guess that many don’t. Even if they knew what they meant it can even more difficult to understand which situations warrant each DOCTYPE. I’ve seen many situations in corporations where a developer copies and pastes a DOCTYPE from another document or will use a template and never think about it.

You can find more information about all of these DOCTYPEs and browser modes in an interesting write up from <a href=”https://twitter.com/hsivonen”>Henri Sivonen</a> entitled <a href=”https://hsivonen.iki.fi/doctype/”>Activating Browser Modes with Doctype</a>.

<h4>New HTML5 Way</h4>

&lt;!DOCTYPE html&gt;

Thankfully this is a much simpler way to declare the DOCTYPE. We now have one DOCTYPE to chose from and it is short and sweet.

I’ve already mentioned that we can use this new DOCTYPE today. But what about older browsers? If clients use a browser that doesn’t recognize the HTML5 DOCTYPE then it will switch the content into standards mode and not quirks mode. Unless you have a specific reason to cater to browser modes, start using the new DOCTYPE declaration and take advantage of all the HTML5 goodness in your web application.

<h3>Simplified Encoding</h3>

HTML5 has also provided a simplified approach in the the way we indicate the character encoding used for the document.

<h4>Old Way</h4>

&lt;meta http-equiv=&quot;Content-Type&quot;
content=&quot;text/html; charset=utf-8&quot;&gt;

<h4>New HTML5 Way</h4>

&lt;meta charset=&quot;utf-8&quot;&gt;

Interestingly current and older browsers already support this shortened syntax and we can use it right away in web applications. You can read more about this and other interesting details from <a href=”https://twitter.com/diveintomark”>Mark Pilgrim</a>’s detailed explanation in <a href=”https://diveintohtml5.org/semantics.html”>Dive into HTML 5: What Does It All Mean?</a>.

<h3>Simplified Script, Style, and Link elements</h3>

Another simplification in HTML5 is to make the type parameter optional on the script, style, and link elements. If we don’t provide the type attribute, then their defaults will be “text/javascript” for script tags and “text/css” for style and link tags. That means that we can leave out the type attribute in the majority of our uses of these elements. The great thing is that we can also use these techniques today in our web site and it will be supported in older browsers as well.

<h4>Old Way</h4>

&lt;link rel=&quot;stylesheet&quot; href=&quot;site.css&quot; type=&quot;text/css&quot; /&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 { color: red; }
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;common.js&quot;&gt;&lt;/script&gt;

<h4>New HTML5 Way</h4>

&lt;link rel=&quot;stylesheet&quot; href=&quot;site.css&quot; /&gt;
&lt;style&gt;
h1 { color: red; }
&lt;/style&gt;
&lt;script src=&quot;common.js&quot;&gt;&lt;/script&gt;

<h2>Semantic Elements</h2>

<div class=”note”>The following section includes new HTML5 technologies that we can use today as well as the work arounds we can implement to obtain older browser support.

</div>

There was a time when websites were commonly designed by using table element after table element to create complex layouts. Recently most designers heavily use the div element to float their way to equally complex and versatile layouts. HTML5 continues to transition web design by introducing new elements that make layouts more explicit.

<h3>New HTML5 Elements</h3>

Instead of overly using divs across our web application we can use the new HTML5 <code>header</code>, <code>footer</code>, <code>article</code>, <code>section</code>, <code>nav</code>, <code>menu</code>, and <code>hgroup</code> elements. These additions are more semantics than anything else. We could just as easily keep them as divs, but by using the new elements it makes your markup much more recognizable and easier to navigate.

Let’s take a simple scenario and see how it changes our markup. A common thing to include in a website is a header section. Normally we just use a <code>div</code> element and give it an id of “header”. However, we can just use the new semantic HTML5 element <code>header</code> instead.

<h4>Old Way</h4>

&lt;div id=&quot;header&quot;&gt;
&lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
&lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
&lt;/div&gt;

<a href=”https://jsbin.com/ajici4/4/edit”>JS Bin demo</a>

<h4>New HTML5 Way</h4>

&lt;header&gt;
&lt;hgroup&gt;
&lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
&lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
&lt;/hgroup&gt;
&lt;/header&gt;

<a href=”https://jsbin.com/ageti/3/edit”>JS Bin demo</a>

Other than simply just replacing the <code>div</code> element with a HTML5 <code>header</code> element, you might also notice that I introduced the idea of using a <code>hgroup</code> element. This is another new HTML5 element that is meant to group section headings (i.e. <code>h1</code>, <code>h2</code>, <code>h3</code>, etc…). The benefit of this is that the items in the <code>hgroup</code> don’t affect the overall outline of the document. This means that we can have a heading and sub-heading without changing the outline layout of the document.

<h2>Support for Older Browsers</h2>

As long as a client is using a browser that can understand HTML5 our page will render properly. When someone renders our updated website with a non-HTML5 complaint browser (such as Internet Explorer), there are some things that we’ll need to consider.

Current released versions of Internet Explorer can’t understand the new HTML5 elements, so we’ll need to add some additional JavaScript code to help. We can either create the HTML5 elements manually, use the <a href=”https://www.modernizr.com/”>HTML5 Shiv</a> library, or use the <a href=”https://www.modernizr.com/”>jQuery Modernizr Plugin</a>. Let’s cover each of these in more detail.

<div class=”note”>Internet Explorer 9 is intended to support HTML5 but it is currently only in the early phase of development. The beta version of Internet Explorer 9 will be released on <a href=”https://mashable.com/2010/08/12/ie9-beta/”>September 15, 2010</a>. Until then you can download the <a href=”https://ie.microsoft.com/testdrive/”>latest preview bits</a> and play around with them.

</div>

<h3>Creating HTML5 Elements Manually</h3>

We can always create the HTML5 elements manually. It isn’t difficult to do. We just need to call the createElement method off the of the document and pass the new element’s name. At that point, the browser will recognize the new element and be able to apply styles to it.

document.createElement(&quot;header&quot;);
document.createElement(&quot;footer&quot;);
//etc...

<h3>Creating HTML5 Elements with HTML5 Shiv</h3>

Why do something by hand when someone has already done it for us? <a href=”https://twitter.com/rem”>Remy Sharp</a> has created a library called <a href=”https://code.google.com/p/html5shiv/”>HTML5 Shiv</a> that already does the manual creation of HTML5 elements for us. The library is hosted on Google Code and we can integrate it in our project by including the following lines in the head section of the document.

&lt;!--[if lt IE 9]&gt;
&lt;script src=&quot;https://html5shiv.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
&lt;![endif]--&gt;

<h3>Creating HTML5 Elements with Modernizr</h3>

Another way that we can create the new HTML5 elements is to use the <a href=”https://www.modernizr.com/”>Modernizr JavaScript Library</a> that <a href=”https://twitter.com/paul_irish”>Paul Irish</a> and <a href=”https://twitter.com/KuraFire”>Faruk Ateş</a> developed. The library creates all the new HTML5 elements we need while it is loading on the page. All we need to do is to include the script tag inside of the head element before we style our HTML5 elements.

&lt;script src=&quot;modernizr-1.5.min.js&quot;&gt;&lt;/script&gt;

The library really does much more than just create the new HTML5 elements. Its purpose is to detect which features a client browser supports and allows us to develop your web application using progressive enhancement techniques. The scope of the plugin is much too large for this particular blog post, but I encourage you to check it out.

If you plan to use some of the advanced features of Modernizr, then it will already create the new HTML5 elements for you. If you don’t plan on customizing the experience based on the features of the current browser, then your best bet is to use the HTML5 Shiv or manually create the HTML5 elements yourself in code.

<h3>Styling the HTML5 Elements</h3>

Now that we’ve managed to make older browsers understand the HTML5 elements we need to focus on styling them correctly.

On creation the elements will have a default display style of “inline”. In order to style them correctly we’ll likely need to change their style to “block” instead. This can be done very easily with the following section of code.

header, footer, article, section, nav, menu, hgroup {
display: block;
}

<h3>Dynamic Insertion of HTML5 Elements</h3>

As, it turns out there is another caveat that we need to account for when using HTML5 elements in Internet Explorer. If we try to add HTML5 elements to the DOM dynamically it will not recognize the new element and therefore won’t style it appropriately.

Thanks to <a href=”https://twitter.com/jdbartlett”>Joe Bartlett</a>, there is a script called <a href=”https://jdbartlett.github.com/innershiv/”>HTML5 innerShiv</a> that will resolve this issue. You can find more information about usage of this script on <a href=”https://twitter.com/chriscoyier”>Chris Coyier</a>’s blog post entitled <a href=”https://css-tricks.com/html5-innershiv/”>Fix Inserted HTML5 Content with HTML5 innerShiv</a>.

For example, instead of just appending a new HTML5 element to the DOM, we would first wrap it in the innerShiv method.

$('header').append(innerShiv(&quot;&lt;nav&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/nav&gt;&quot;));

<h2>A Larger Before vs After Example using HTML5 Semantic Elements</h2>

<div class=”note”>The intent of this section is not to explain the nuances of when and when not to use each of the new HTML5 Semantic Elements, but it is rather an example of how a layout could be changed utilizing the new elements. You can learn more details about each of the HTML5 elements from the <a href=”https://html5doctor.com/glossary/”>HTML5 Doctor Glossary</a>.

</div>

To give you an idea of how the format of your page layout might change, I’ve included the following markup snippets. The first code snippet shows how you might organize the markup with HTML 4 and the following snippet shows how you might organize it with the new HTML5 semantic elements.

<h4>Old Way</h4>

&lt;div id=&quot;header&quot;&gt;
&lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
&lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
&lt;div id=&quot;navigation&quot;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;sidebar&quot;&gt;
&lt;h1&gt;Twitter&lt;/h1&gt;
&lt;blockquote cite=&quot;https://twitter.com/elijahmanor/status/20313555458&quot;&gt;
1st day at @appendTo I wrote Aug Tips for @ejquery website. Let me know if you found helpful, thnx https://j.mp/ejquery
&lt;/blockquote&gt;
&lt;/div&gt;
&lt;div id=&quot;posts&quot;&gt;
&lt;div class=&quot;post&quot;&gt;
&lt;div class=&quot;header&quot;&gt;
&lt;h3&gt;I'm looking for a Job&lt;/h3&gt;
&lt;/div&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;p&gt;Well, it's a funny story involving the FBI and IRS raiding...&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;footer&quot;&gt;
&lt;p&gt;Published &lt;time pubdate datetime=&quot;2010-07-08T12:21-07:00&quot;&gt;8, July 2010&lt;/time&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;footer&quot;&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

<h4>New HTML5 Way</h4>

&lt;header&gt;
&lt;hgroup&gt;
&lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
&lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
&lt;/hgroup&gt;
&lt;nav&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/nav&gt;
&lt;/header&gt;
&lt;aside&gt;
&lt;h1&gt;Twitter&lt;/h1&gt;
&lt;blockquote cite=&quot;https://twitter.com/elijahmanor/status/20313555458&quot;&gt;
1st day at @appendTo I wrote Aug Tips for @ejquery website. Let me know if you found helpful, thnx https://j.mp/ejquery
&lt;/blockquote&gt;
&lt;/aside&gt;
&lt;section&gt;
&lt;article&gt;
&lt;header&gt;
&lt;h3&gt;I'm looking for a Job&lt;/h3&gt;
&lt;/header&gt;
&lt;content&gt;
&lt;p&gt;Well, it's a funny story involving the FBI and IRS raiding...&lt;/p&gt;
&lt;/content&gt;
&lt;footer&gt;
&lt;p&gt;Published &lt;time pubdate datetime=&quot;2010-07-08T12:21-07:00&quot;&gt;8, July 2010&lt;/time&gt;.&lt;/p&gt;
&lt;/footer&gt;
&lt;/article&gt;
&lt;/section&gt;
&lt;footer&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/footer&gt;

<h2>Templates to Get You Started</h2>

Recently three separate projects have formed to help you get quickly started with HTML5 development in your next project. These projects address many of the concerns we’ve addressed above, but also touch on topics that we haven’t yet addressed.

<ul>
<li><a href=”https://html5boilerplate.com/”>HTML5 Boilerplate</a> by <a href=”https://twitter.com/paul_irish”>Paul Irish</a> and <a href=”https://twitter.com/nimbupani”>Divya Manian</a> – This template is probably the most comprehensive I’ve seen. It includes a host of features that you’ll need to start a new HTML5 web application. It addresses the concerns we’ve mentioned in this article, but it also handles mobile optimizations, optimal caching rules, progressive enhancement using Modernizr, CDN hosted jQuery with local failsafe, plus much more. You’ll most likely use this template as a starting point and then delete the things that may not be pertinent to your web application.</li>
<li><a href=”https://html5reset.org/”>HTML5 Reset</a> – This template is slightly less comprehensive as the Boilerplate, but still provides a great amount of features that you’ll most likely need in your next HTML5 web application. Some of these features include cross-browser concerns, progressive enhancement using Modernizr, and many others.</li>
<li><a href=”https://github.com/dcneiner/html5-site-template”>HTML5 Site Template</a> by <a href=”https://twitter.com/dougneiner”>Doug Neiner</a> – This template is the most simple alternative to the above two templates. It includes the concerns we’ve addressed in this article, but leaves out some of the extra stuff that you may not need in your web application. If you are overwhelmed with the amount of options from the first two templates, this might be a good place for you to start. Then, if you find yourself in need some of additional features, you can reference the above templates for their implementation.</li>
</ul>

<h2>Conclusion</h2>

Although not all browsers have the same level of support for HTML5, you can still start using many of the syntactical and semantic features that it provides. With a few considerations you can use these features without worrying about backwards compatibility.

As for future blog posts we will look at the following topics:

<ul>
<li>Part 2: Form Enhancements</li>
<li>Part 3: Local &amp; Session Storage</li>
<li>Part 4: Video &amp; Audio Elements</li>
</ul>