Faded gradient separator bars

Here is a technique for creating both horizontal and vertical separator bars with pure css.

See the Pen Sexyline 2 – verticlal by Michael Jasper (@mdjasper) on CodePen

Using CSS3 radial gradients positioned off element, just the tip of the gradient is show, giving the line a nice shadowed/faded look:

This technique can be applied to <hr>  tags for semantic breaks in content, or they can be applied to any element or class as an effect.

See the Pen Sexyline 2 by Michael Jasper (@mdjasper) on CodePen

Properly aligning and wrapping image captions

Easily align and wrap captions to images of unknown size with two relatively unknown CSS properties.

I recently learned a new css trick to align and wrap captions properly to images of unknown size.  This is a common problem when dealing with any content management system that allows users to upload images to pages or articles.

The problem:

This is a caption of slightly longer length. It should wrap, regardless of the size of the image.

The css solution:

This is a caption of slightly longer length. It should wrap, regardless of the size of the image.

Voilà!

Front-end Series: JavaScript debugging tips and tricks

Note: many of these tips are written with Chrome in mind, but are applicable to any modern browser with developer tools.

  1. Understand what is happening in your code
  2. Set and use Breakpoints
  3. Use the Console api
  4. De-minify
  5. Modify scripts locally
  6. Use a Unit-Testing framework

1. Understand what is happening in your code

A prerequisite to debugging is understanding the code in question. Before debugging, you should be able to answer: what is the purpose of this function? What should the parameters be? How will this line affect local and global variables?

Basically, run the code mentally before trying to debug.

2. Set and use Breakpoints

Once you understand how the code should function, set execution breakpoints at key places. When reached, a breakpoint will pause the execution of script on that line. You can then “step-through” the code one line at a time. This view also allows you to inspect any global or local values to ensure they are what you expect them to be. Often times, you can observe a variable which should contain a value, but is undefined. From there it is easy to trace your way back up and see where the error is occurring.

Breakpoints can be set by clicking on the line-number in the script tab of chrome developer tools, or programmatically using the  debugger; directive.

debug-breakpoints

Use the console api

While sprinkling a few  console.log ‘s sparingly throughout your code can be useful, the console api has many useful functions that might serve the purpose better. Here are a few console api methods I have found useful:

console.dir

Displays all the properties of an object.

console.dir

 console.table

Formats arrays and objects as tables, and allows sorting on columns.
console.table

console.time

Starts and stops a timer (string tag based), logs time (in ms) of intermediate code.
console.time

console.memory

Returns heap information for this process.
console.memory

console.trace

Returns a stack trace for the function where it is called.

console.trace

4. De-minify

When debugging, it can be very frustrating to see an error like:

When at all possible, swap out the minified version for a full expanded and commented version of the script.

When a full version is not available, Chrome’s developer tools come to the rescue. The curly brace button below the script will automatically expand lines for better breakpointing and debugging. It does not however rename obfuscated variable names.
de-minify

Minification bugs

Every so often, you can run into the maddening bug of a full script working, and the same minified script breaking. Luckily, these bugs often attributable to one of a few small problems (mostly having to do with missing semicolons).

For example:

These bugs can also creep in from preceding scripts, or when multiple scripts are concatenated together. This is the reason that jQuery plugins typically start with a  ; . It is a preventative measure against misbehaving code above it.

5. Modify scripts locally

Chrome allows you to modify script files and run them locally. Simply double click into source file, type, and CTRL-S to save. Not much more to explain, but very useful trick!

6. Use a Unit Testing framework

There are a handful of very good third-party unit-testing frameworks for JavaScript, each with their own philosophy and syntax.

See this great Stack Overflow post for many more.

Front-end Series: Part 1 – Architecture

This is part 1 in the Front-end Series. As a front-end developer at a large organization, I work daily on architecture, performance, automation, localization, and compatibility, and other topics which I will share during this series. Feel free to post topic ideas in the comment section!

Large scale web application architecture is much more than a server and a /www folder. The build process can scale with need, but the basic setup contains building assets to a development area, then production environment, caching, and delivery via cdn.

This is example architecture diagram — showing building to different environments, pushing to cdn boxes, and caching.

Front-end-archetecture

Building static assets via source control

Working with other developers at any scale necessitates use of a version control system. Whether Git, Subversion, Mercurial, or the next new hotness, a DVCS is an absolute must. After developing in a local environment, assets are pushed to a development version-controlled server.

The assets here are never directly used by the application, but are pushed to a CDN server (or a mock-cdn for development).  The source control and CDN can be can be synchronized by a few different methods:

  • CRON task that rebuilds one folder from the other
  • Post-commit hook that runs similar script
  • 3rd party build software, like Anthill

Server environments, or “lanes”

It’s necessary to duplicate asset servers for different audiences. The most basic are:

  • Development
  • Testing
  • Staging
  • Production

A typical pipeline is:

  • Assets are developed locally
  • Files are moved into the Development environment to be integrated with other developers work and preliminary tested
  • Quality Assurance tests the application.  Feedback provided to developers (loop back)
  • Once testing is successful,  the assets are moved to the staging server, which serves as a place for stakeholders to preview the application, and approve it for production
  • When okay-ed, the files are moved to production where they are publicly accessible. They are now “live”

Caching and Content Delivery

Linking directly to assets on a server is an excellent way to kill your site, when it goes viral (the Reddit hug of death, or the slashdot effect). The most basic level of defense is on server caching. On smaller sites, this can be an effective protection. Many CMS’s (like WordPress) have plugins that can caching dynamic content (php generated files saved as static html). WP-SuperCache is an excellent example of this layer of defense.

The second layer of defense is a Caching Appliance. This is a server (or cluster of servers) that specializes in serving static files with extreme speed. This appliance has only one function, which allows it to maximize its resources for the one purpose of serving content.

The top layer for serving files is utilizing a Content Delivery Network to distribute and cache assets globally.  At it’s core, a CDN is a network of servers placed in strategic locations around the world, each containing duplicate and synchronized files. These servers, ideally located on backbone connections, serve files to customers quickly in different areas of the globe. For example, a user in France is served assets from a UK server, rather then making the transatlantic trip to Virginia.

For smaller sites (such as this one) there are free or inexpensive CDN options. This website uses CloudFlare to serve static assets to viewers (your CSS file was probably served from this CDN, reducing my server load. Yay!) An excellent CDN for large-scale websites is Akamai. You’ve almost certainly been served assets from Akamai (Facebook, Adobe, Microsoft, and many more use it).  If you’re in the market, take a look at CloudFront as well.

So there you have it: The front-end build and architecture for one of the largest publishing organizations in the world!

Big Picture

What I’ve described is the front-end server and building process for a large scale web application. This setup will typically be mirrored by the application codebase (back-end).

back-end-architecture

Comments, feedback or criticism? Let me know in the comments:

Creating your own JavaScript Library – part 2 – Event Handling

write-your-own-javascript-libraryIn Part 1 of Creating your own JavaScript library, we cover the library essentials: library design, creating a solid object constructor, and adding functions by extending the object prototype. This post focuses on extending our basic library with event handling.

Out of the box event handling can be accessed  through Javascript and DOM apis, shown in the first 3 examples:

Simple event handling:

Assigning functions to events this way can be problematic, as only one function can be assigned at any given time. Mozilla Developer Network recommends that the addEventListener method be used instead, because of its flexibility.

Better Event handling

The addEventListener method accepts three parameters:

Assigning an anonymous function:

We can easily wrap this built in functionality with our library by creating a click function with a parameter that is passed to this native DOM event. This parameter will be an anonymous function (like the previous example) that will then bound to the element’s handler.

Handler wrapped by our library:

This pattern can be applied to any event natively exposed, such as:

  • onclick
  • onmouseover
  • blur
  • keydown

Non-standard or browser specific events

In the case where one browsers event api differs, it is simple to account for this in our event handler:

Optimizing our code

Instead of duplicating the addEventListener code in each event wrapper, we can optimize by creating an internal addListener(event, callback) function which will be called by other exposed functions, such as click, onMouseOver, etc

This separates the public wrapper from the internal event binding, allowing us to easily modify or expand the actual event binding code without modifying it in numerous places

 

Software Engineering principles applied to CSS

Some of my thoughts about CSS developent. Think of more? Share in the comments and I’ll add them to this page!

Low Coupling

The principle of low coupling suggests that distinct parts of an application be as “stand-alone” as possible.

To illustrate: A very decoupled program could be available from the command-line first, then a GUI is built using that programs API’s. This ensures that the logic of the program is decoupled from the presentation. A developer can change the internal workings of the program without affecting the other aspects of the architecture.

Targeting elements based on their DOM order tangles up the visual presentation (CSS) with the structured content (HTML) – Highly coupling the presentation with the content.

Changing the name of your parent container shouldn’t detach your horizontal menu from its style.

Separate the presentation from the structure with the use of classes:

High Cohesion

Separating the concerns of CSS into different files allows you to create highly cohesive classes that, once in place, allow a great deal of flexibility in development. Areas of concern are:

  • Layout: positioning of elements, geometric dimensions
  • Style: colors, borders, backgrounds
  • Normalization: typography, element defaults

Separating the CSS into separate areas allows you to create highly cohesive “modularized” rules that have the bonus of being easily swappable:

  • Layout-full.css, layout-compact.css
  • Blue.css, green.css, red.css
  • Normalize.css

Any combination of the above files could be used to alter the presentation of the application without changing the content architecture.

Inheritance

If elements are targeted by semantic classes, instead of their order in the DOM, it is easy to modularize classes using the principle of inheritance:

This is a popular technique in many rapid development frameworks, such as Bootstrap, Zurb, and others.

Additionally, CSS may use the principle of multiple inheritance by using styles from multiple sources – such as a horizontal navigation getting its form and function from layout.css, and its color and branding from color.css files.

Generalization

In software engineering, the most general use-case is often sought, as it will eliminate redundant future work. Nathanial Borenstien, inventor of the MIME type once said,

“It should be noted that no ethically-trained software engineer would ever consent to write a DestroyBaghdad procedure. Basic professional ethics would instead require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter.”

Name classes based on their general use-case, rather than on their appearance, position, or other attribute.

If not, ‘The boss’ might ask you to change the submit button to green, but the in-code class will stay .button-blue  forever, because it is already in hundreds of places.

Naming classes on their general case avoids this problem, and also makes for easy discovery and maintenance by future programmers, or your future self.

Additionally, duplication of elements becomes easier. If not, you might need to duplicate the element somewhere other than the original place, and you end up with navigation in the footer called  .sidebar-nav

Abstraction

If using the principle of generalization, there may be some base class that is never intended to be used on an element on its own. To provide some level of abstraction, only declare universal attributes on parent classes.

Encapsulation (private styles)

By using the principle of inheritance, we can make some classes essentially private by namespacing their selector rules:

This ensures our style definitions don’t ‘leak’ into other elements, and can only be used within a specified parent element.

Custom events system in JavaScript – LightEvents.js

Needing an event subscription and publishing system for a HTML5/canvas game I’m creating, I wrote a very light event system.

Anything than can call JavaScript (link, button, etc) can raise an event:

LightEvents.publishEvent('event name', data);

Subscribing to events is equally easy:

Here is the LightEvents object, demo is embedded below

JS Bin

Quick and reliable ad-rotator

In the course of my work, I’ve created and refined a simple ad rotator. It is built in JavaScript, and does not rely on any library, like jQuery, to function.  In my experience, it defeats ad-block, and loads easily on all mobile, tablet, and desktop browsers.

The rotator can be included multiple places on one page without any conflicts or collisions, so just drop-in where needed. Some coding is required to customize — basically copying and pasting your links and image urls, but nothing too heavy.

 

asp.net – getting user confirmation before a postback

In asp.net web applications, it is common to have dozens — if not hundreds — of user controls that perform postbacks to the server, actions initiated by a user such as a button click. Often before a save, delete, or other critical action is performed, it is desirable to ask the user if they are sure.

In Asp.net web applications, buttons and other controls have two event properties that we are concerned with: onClick , and onClientClick .

The onClick event calls a specified function in the code-behind file. At this point, the postback has occurred, and any confirmation would have to take place with another rendered page — meaning lots of wasted time and wasted resources.  With the onClientClick event, we can interrupt the onClick event with our own javascript function or inline statement.

Using jQuery, we can bind function to all of these “confirm-able” user controls, which will interrupt the default post-back behavior  presenting users with a confirmation dialog box:

Using this method, we can target all user controls with the CSS class confirm. Additionally, if we wanted a broader reach, we could modify the jQuery selector to  input[type=button] or for all buttons, or all links.

The confirm box  var response = confirm("Are you sure?"); used in this example is a default JavaScript confirmation dialog box — which will be rendered differently per browser or platform — but you could easily swap this for any other confirmation script or function that returns a boolean value.

Creating a microformat / richsnippits resume

What are microformats?

Microformats are small patterns of HTML to represent commonly published things like peopleeventsblog postsreviewsand tags in web pages.

Microformats are the quickest & simplest way to provide an API to the information on your website. See what else you can do with microformats.

Have you ever searched for a recipe on Google, and wondered how the highlight data like ingredients or cook time on the search results? Microformats. Or, wondered how they can aggregate reviews, locations, and prices for a restaurant search? Microformats.

Make your resume semantically searchable and available by implementing microformats.

There are several types we will implement from the microformat standard, schema.org, for fields on our resume:

  • http://schema.org/Person
  • http://schema.org/PostalAddress
  • http://schema.org/CollegeOrUniversity
  • http://schema.org/Organization

Resume Sample

View the resume here, and a Google’s report on extracted data here.