Archive for November, 2012

Building A Relationship Between CSS & JavaScript


  

jQuery, Prototype, Node.js, Backbone.js, Mustache and thousands of JavaScript microlibraries all combine into a single undeniable fact: JavaScript is popular. It’s so popular, in fact, that we often find ourselves using it in places where another solution might be better in the long run.

Even though we keep JavaScript, CSS and HTML in different files, the concepts behind progressive enhancement are getting all knotted up with every jQuery plugin we use and with every weird technique that crops up. Because JavaScript is so powerful, there are a lot of overlaps in capability between JavaScript and HTML (building document structure) and JavaScript and CSS (injecting style information). I’m not here to pick on any JavaScript library, bootstrap or boilerplate; I’m just here to offer a little perspective as to where we are and how we can realign our goals.

Relationship Image
Image Credit: opensourceway.

Keeping CSS Out Of Your JavaScript

CSS can hook into HTML with a variety of different selectors; this isn’t anything new. By using IDs, classes or any attribute you can think of (even custom attributes), you have easy access to style an element. You can also do this with a slew of JavaScript methods, and honestly, it’s the same basic process with a different syntax (one of my JavaScript ah-ha moments). Being able to natively access HTML from JavaScript and from CSS is one of the reasons progressive enhancement has been such a successful development model. It allows a point of reference to guide us and to serve as a reminder as we develop a project, so we don’t “cross the streams”.

But, as you move forward with JavaScript and build applications with highly interactive elements, it gets harder to not only keep HTML out of your JavaScript, but also to catch yourself before injecting style information into a document. Of course, the case for not injecting style with JavaScript certainly isn’t a binary one (yes/no, true/false, 0/1); there are plenty of cases where you might need to apply styles progressively, for example, in a drag and drop interface where positioning information needs to be constantly updated based on cursor (or finger) position.

But generally speaking, you can safely house all the style information you need within CSS and reference styles as reusable classes. This is a much more flexible model than sprinkling CSS throughout a JavaScript file, and it very closely compares to the model of adding style information into your HTML. We follow this model when it’s only HTML and CSS, but for some reason it has a tendency to fall apart once JavaScript gets added into the mix. It’s certainly something we need to keep an eye on.

A lot of front-end developers take real pride in having clean HTML. It’s easy to work with, and to certain super-geeks it can even be artful. It’s great to have clean, static HTML, but what good is that if your generated HTML is riddled with injected style and non-semantic markup? By “generated HTML,” I’m referencing how the HTML looks after it’s been consumed and barfed back up after being passed around all those plugins and extra JavaScript. If step one to having clean HTML and separated progressive enhancement layers is to not use a style attribute, I’d have to say that step two is to avoid writing JavaScript that injects a style attribute for you.

Cleaning Up Your HTML

We can probably all agree that blindly using a technology is a terrible idea, and I think we’re at a point with jQuery where we are, indeed, blindly using a lot of the features without fully understanding what’s going on under the hood. The example I lean on pretty heavily for keeping CSS out of my JavaScript is the behavior of jQuery’s hide() method. Based on the principles of progressive enhancement, you wouldn’t code something with inline CSS like this:

<div class="content-area" style="display:none;"></div>

We don’t do that because a screen reader won’t pick up an element if the style is set to display:none, and it also muddies up the HTML with unnecessary presentational information. When you use a jQuery method like hide(), that’s exactly what it does: it will set a style attribute on the target area and add a display property of none. It’s very easy to implement, but not very good for accessibility. It also violates the principles of progressive enhancement when you inject style into the document like that (we’re all sorts of messed up, huh?). It’s not uncommon for this method to be used within a tabbing interface to hide content. The result is that the content is nonexistent to a screen reader. Once we realize that adding style from JavaScript isn’t ideal in most cases, we can move it into the CSS and reference it as a class:

CSS

.hide {
   display: none;
}

jQuery

$('.content-area').addClass('hide');

We still have to address the accessibility problem of hiding content with display:none, but since we’re not using a built-in jQuery method anymore, we can control exactly how content gets hidden (whichever accessible method you prefer is probably fine). For example we could do something like:

CSS

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

.remove {
   display: none;
}

In the above example, you can see that even though both classes result in content being removed from view, they function very differently from an accessibility standpoint. Looking at the code like this makes it clear that we really are dealing with style information that belongs in a CSS file. Using utility classes in this way can not only help your JavaScript slim down, but also have double usage in an Object Oriented CSS (OOCSS) development model. This is truly a way to not repeat yourself (Don’t Repeat Yourself, or DRY) within CSS, but also across a whole project, creating a more holistic approach to front-end development. Personally, I see a lot of benefit in controlling your behaviors this way, but some people have also called me a control-freak in the past.

Web and Team Environments

This is a way we can start opening up lines of communication between CSS and JavaScript and lean on the strengths of each language without overdoing it. Creating a developmental balance on the front end is very important, because the environment is so fragile and we can’t control it like we can on the back end with a server. If a user’s browser is old and slow, most of the time you can’t sit down and upgrade it (aside: I do have my grandmother using Chrome); all you can do is embrace the environmental chaos, build for the best and plan for the worst.

Some people have argued with me in the past that this style of development, where you’re referencing CSS classes in JavaScript, doesn’t work well in team development environments because the CSS is usually built by the time you’re diving into the JavaScript, which can cause these classes to get lost in the mix and create a lot of inconsistency in the code (the opposite of DRY). To those people I say: poke your head over the cube wall, open AIM, GTalk or Skype, and communicate to the rest of the team that these classes exist specifically to be used with JavaScript. I know the concept of developers communicating outside of GIT commit messages seems like madness, but it’ll be okay, I promise.

Using Behavioral CSS With JavaScript Fallbacks

Using these CSS objects as hooks for JavaScript can go far beyond simple hiding and showing of content into an area of behavioral CSS, transitions, animations and transforms that are often done with JavaScript animations. With that in mind, lets take a look at a common interaction model of fading out a div on click, and see how it would be set up with this development model, while providing the proper fallbacks for browsers that might not support the CSS transition we’re going to use.

For this example we’ll be using:

First, let’s set up our body element:

<body>
    <button id="do-it" type="button">Run Transition</button>
    <div id="cube"></div><!--/#cube-->
</body>

From there we’ll need to set up the CSS:

#cube {
   height: 200px;
   width: 200px;
   background: orange;
   -webkit-transition: opacity linear .5s;
      -moz-transition: opacity linear .5s;
        -o-transition: opacity linear .5s;
           transition: opacity linear .5s;
}

.fade-out {
   opacity: 0;
}

Before we add on the JavaScript layer, lets take a moment and talk about the flow of what’s going to happen:

  1. Use Modernizr to check for CSS Transition support
  2. If Yes
    1. Set up a click event on the button to add a “fade-out” class to #cube
    2. Add another event listener to catch when the transition is finished so we can time the execution of a function that will remove #cube from the DOM.
  3. If No
    1. Set up a click even on the button to use jQuery’s animate() method to manually fade #cube out.
    2. Execute a callback function to remove #cube from the DOM.

This process will introduce a new event called transitionend, which will execute at the end of a CSS transition. It’s amazing, FYI. There is also a companion event called animationend, which will execute at the end of a CSS animation for more complex interactions.

First thing we need to do is set up our variables in the JavaScript:

(function () {

   // set up your variables
   var elem = document.getElementById('cube'),
       button = document.getElementById('do-it'),
       transitionTimingFunction = 'linear',
       transitionDuration = 500,
       transitionend;

   // set up the syntax of the transitionend event with proper vendor prefixes
   if ($.browser.webkit) {
       transitionend = 'webkitTransitionEnd'; // safari & chrome
   } else if ($.browser.mozilla) {
       transitionend = 'transitionend'; // firefox
   } else if ($.browser.opera) {
       transitionend = 'oTransitionEnd'; // opera
   } else {
       transitionend = 'transitionend'; // best guess at the default?
   }

   //... rest of the code goes here.

})(); // end wrapping function

You might notice that our new transitionend event needs a vendor prefix; we’re doing a little browser detection to take care of that. Normally you might detect for the vendor prefix and add it onto the event name, but in this instance the cases for the syntaxes are a little different, so we need to get the whole name of the event for each prefix.

In the next step we’ll use Modernizr to detect support, and add our event listeners to each case (all of this stuff gets added inside the wrapping function):

// detect for css transition support with Modernizr
if(Modernizr.csstransitions) {

    // add our class on click
    $(button).on('click', function () {
       $(elem).addClass('fade-out');
    });
    
    // simulate a callback function with an event listener
    elem.addEventListener(transitionend, function () {
       theCallbackFunction(elem);
    }, false);
       
} else {

   // set up a normal click/animate listener for unsupported browsers
   $(button).on('click', function () {

       $(elem).animate({
           'opacity' : '0'
       }, transitionDuration, transitionTimingFunction, function () {
           theCallbackFunction(elem);
       });

   }); // end click event

} // end support check

Finally, we need to define a shared function between the two actions (DRY) which executes after the transition (or animation) is complete. For the sake of this demonstration we can just call it theCallbackFunction() (even though it’s not technically a callback function). It will remove an element from the DOM and spit out a message in the console letting us know that it worked.

// define your callback function, what happens after the transition/animation
function theCallbackFunction (elem) {

   'use strict';

   // remove the element from the DOM
   $(elem).remove();

   // log out that the transition is done
   console.log('the transition is complete');

}

In the browser, this should work the same way in IE 7 (on the low end) as it does in mobile Safari or Chrome for Mobile (on the high end). The only difference is under the hood; the experience never changes for the user. This is a way you can use cutting-edge techniques without sacrificing the degraded user experience. It also keeps CSS out of your JavaScript, which was really our goal the whole time.

The Moral Of The Story

You might be asking yourself why we should even bother going through all this work. We wrote about 60 lines of JavaScript to accomplish the same design aesthetic that could be created with eight lines of jQuery. Well, no one ever said that keeping clean code and sticking to progressive enhancement was the easiest thing to do. In fact, it’s a lot easier to ignore it entirely. But as responsible developers, it’s our duty to build applications in a way that is accessible and easily scales to the future. If you want to go that extra mile and create a seamless user experience as I do, then it’s well worth the extra time it takes to dot all the i’s and cross all the t’s in a project to create an overall experience that will gracefully degrade and progressively enhance.

Using this model also lets us lean heavily on CSS for its strengths, like responsive design and using breakpoints to redefine your interaction at the various screen sizes. It also helps if you’re specifically targeting a device with a constrained bandwidth, because, as we all know, CSS is much lighter than JavaScript in both download and execution time. Being able to offload some of the weight JavaScript carries onto CSS is a great benefit.

In production, we are currently using CSS animations and transitions for micro interactions like hover effects and maybe a spinning graphic or a pulsating knot. We’ve come to a point where CSS is a pretty powerful language that performs very well in the browser and it’s okay to use it more heavily for those macro interactions that are typically built using JavaScript. If you’re looking for a lightweight and consistent experience that’s relatively easy to maintain while allowing you to use the latest and greatest browser features — it’s probably time to start mending fences and build strength back into the relationship between CSS and JavaScript. As a great man once said, “The key to writing great JavaScript is knowing when to use CSS instead.” (It was me… I said that.)

(cp)


© Tim Wright for Smashing Magazine, 2012.


Accessible custom checkboxes and radio buttons

Every now and then I’m handed a design comp that has customised checkboxes and radio buttons. This used to make me think “Oh no, not again� because I simply didn’t know of a reliable way to customise these particular form controls.

Sure, if all you care about is replacing the browser default with a custom graphic it isn’t that hard. But if like me you’re also interested in doing so without degrading user experience, especially during keyboard interaction, you have a number of problems to deal with.

Fortunately the situation is a lot better now than it was a few years ago. My first attempts at custom checkboxes and radio buttons involved quite a bit of JavaScript trickery to toggle between different states of the buttons, and I never got it to work perfectly cross-browser, cross-input device. However, since recent versions of all major browsers support the :checked CSS pseudo-class, you can now leave it to the browser to handle the states and focus on the CSS. No JavaScript involved.

Read full post

Posted in , .

Copyright © Roger Johansson


Website Management: An Organizational Structure That Supports Your Digital Presence


  

Which category does your organization’s Web presence fall into? Over- or under-managed? When it comes to the Web, few organizations have found the Goldilocks zone. Their online activities are either under-managed with minimal policies and procedures, or dogged by bureaucracy and internal politics.

Those that fall into the former category are vulnerable to legal threats, internal disputes and knee-jerk management where the website lurches from one crisis to the next. Those in the latter are crippled by indecision and fail to respond to the fast-changing nature of the Web.

How then can an organization’s Web presence receive the oversight it requires, while remaining flexible enough to allow rapid iteration and change? The answer lies in solid Web governance; in particular responsibilities and policies. For example, who is responsible for what?

Responsibilities

Responsibilities for websites are often poorly defined. Either the issue hasn’t been considered, or it has been sidestepped by forming a committee or steering group. In either case, lines of reporting are blurred, responsibilities are ill-defined and priorities on the website are often dictated by who shouts the loudest.

If your website is to be a success, it needs strong leadership, clearly defined roles and people to take responsibility for its success. This can be at least partially achieved using a responsibility assignment matrix.

I know what you are thinking: a responsibility assignment matrix doesn’t sound sexy. I can’t argue with that. However, if you manage to get one signed off, it is going to make life a lot easier. A responsibility assignment matrix is a list of tasks, deliverables and responsibilities related to the running of your website, with individuals assigned to items in one of a number of roles.

A responsibility assignment matrix contains a list of tasks and those individuals involved in completing them.
A responsibility assignment matrix contains a list of tasks and those individuals involved in completing them.

Take, for example, design sign off. This task could be assigned to two people: one who is responsible for sign off, and another who is consulted before a decision is made. By assigning different roles, you clearly define responsibilities and minimize committee decision making. This is crucial for a number of reasons.

  • Committees significantly slow down the decision-making process.
  • Despite what people think, committees are not democratic. They are often dominated by one or two individuals.
  • Committees inevitably lead to compromise as people try to reach a consensus. This results in insipid design that offends nobody but fails to excite anybody.
  • Committee decision making is often more about internal politics than user needs or the success of the project.

Not only will role assignment reduce committee decision making, it will also identify who is responsible for decisions. This will reduce the likelihood of important tasks slipping between the gaps. There are various approaches to the responsibility assignment matrix, but most include at least four roles.

Responsible

Those responsible for a task are those who do the work and make the task happen. For example, in the case of design sign off, this would be the designer. This person could be a part of an internal team or an outside contractor.

Those people assigned the role responsible are those who actually do the work. In some cases they are the person accountable for the task, but it may also be somebody else (typically a subordinate).
Those people assigned the role “responsible” are those who actually do the work. In some cases they are the person accountable for the task, but it may also be somebody else (typically a subordinate).

Accountable

Every task should have a single person who is accountable for its successful completion. This is the person with whom the buck stops and who signs off the task as complete. In the case of design sign-off, this is typically the project manager or client.

There can only be a single person accountable for a task's success. Otherwise, a task can fall between the gaps. It is also worth noting that a responsibility assignment matrix is useful for identifying gaps in your staffing. These can be overcome through outsourcing or recruitment.
There can only be a single person accountable for a task’s success. Otherwise, a task can fall between the gaps. It is also worth noting that a responsibility assignment matrix is useful for identifying gaps in your staffing. These can be overcome through outsourcing or recruitment.

Consulted

You consult those whose opinion is required before a task can be signed off. These are typically the people with an expertise relating to the task or a stake in a successful outcome.

Although a wider circle of people can be consulted on tasks, this should still be limited to those with a related expertise.
Although a wider circle of people can be consulted on tasks, this should still be limited to those with a related expertise.

Informed

These are people who need to be kept informed about the task, but do not contribute to its completion. It may be that they are only informed when the task is completed, or they might be updated at various points throughout the process.

Typically those who are informed make up the largest group. It can easily include entire departments.
Typically those who are informed make up the largest group. It can easily include entire departments.

Minimize the number of people consulted, move them instead into the informed group. Those consulted should be limited to those with a real understanding of the task, or a valuable contribution to make. For example, if the task relates to technical infrastructure, only those with an understanding of technology should be consulted.

More controversially, the same should be true for design sign off. Only those who have a design background or who are responsible for corporate branding should be involved in this decision. After years of working with clients to implement technical projects and agree on design, I can testify that this approach will improve the quality of decision making.

It will also minimize the time required to make decisions, and reduce the staff hours wasted attending meetings where individuals have little to contribute. The challenge is dealing with people who wish to be consulted when they should only be informed. In my experience, the trick here is to agree upfront on the criteria involved in being a consultant before assigning specific people to the task.

For example, you could agree that all tasks should have no more than six people who are consulted. These people should be chosen based on experience relating to the task, or how greatly the outcome impacts them. Once this ‘policy’ is agreed on, the decision making about who should be consulted becomes much less contentious, because it is less personal.

If somebody isn’t included, it isn’t a personal slight, but an application of the policy. Obviously, this won’t keep everybody happy, and sometimes you may be forced to include individuals you would prefer not to. However, this is better than a large committee making decisions on everything.

Also it better defines people’s roles. Those who are consulted aren’t those making the final decision and they will know that going in. Equally those who have been assigned responsibility for a task will be under no illusions that the buck stops with them. Although defining responsibilities and roles will go a long way to improving the structure that supports your digital presence, there is still more that can be done. You can also establish policies.

Establishing Policies

A lot of decisions about digital strategy are knee-jerk reactions. One day, the CEO gets it into their head you need an iPhone app, and so that becomes the number one priority. Another day, a blind user complains that your website doesn’t work with screen readers, and accessibility jumps to the top of the agenda. This approach is ineffective, dangerous and can lead to bad decisions being made in the heat of the moment. It can also result in something being ignored entirely.

So where should you begin, what policies should you establish first? There are a huge variety of areas that can benefit from having policies in place. However, I recommend starting with three:

  • Business objectives & key performance indicators (KPIs),
  • Content management, and
  • Development roadmap.

Let’s look at each in turn.

Business Objectives & KPIs

It shocks me how many organizations do not have clearly defined objectives for their website, and no way of measuring its success. Having an agreed-upon set of objectives and KPIs provides focus to your website. It also acts as a measure against which to resolve disagreements and judge the value of new features.

For example, if it has been agreed that your website’s primary business objective is to generate quality leads, it is easier to argue against suggestions that undermine this. For example, forcing users to hand over their email addresses before being able to access certain content (such as product demonstrations). Although this may generate more leads, it does not meet the quality criteria as most users will not be ready to buy.

So what should these business objectives look like? They don’t need to be complex or take a long time to write. Normally, half a dozen objectives is more than enough. For example Smashing Magazine’s business objectives might be:

  • Generate quality content that encourages users to return regularly to the website;
  • Display relevant advertising in a way that will attract users’ attention, without being annoying;
  • Encourage users to subscribe to email or RSS updates;
  • Generate revenue through the sale of quality books that meet users’ needs; and
  • Encourage users to engage with Smashing Magazine through comments and social networks.

Having a list of objectives is not enough. You also need to prioritize them. If objectives are not prioritized, they will conflict. The result of this is that arguments will arise internally about what should be most prominent on the homepage or what should appear in the website’s navigation.

Finally, monitoring KPIs provides objective evidence about what is working on the website and what is not. This can be invaluable if you need justification for removing content.

Removing Content and Content Management

Content management systems have transformed the way we manage the content of our websites, but they do bring with them some drawbacks. They allow large numbers of people to add content, and this creates challenges around keeping content up-to-date, on-message and relevant. Many organizations suffer from content bloat, where content is constantly added to their website and never removed. Having a policy for managing content is important when more than one or two people are updating the website.

Your policy should answer questions such as these.

  • Who is responsible for ensuring the accuracy of the website’s content?
  • Who is responsible for maintaining the website’s tone of voice?
  • How is content going to be checked for accuracy?
  • Whose approval is required before content can be posted online?
  • How is out-of-date or legacy content going to be managed?

One of the biggest challenges associated with content management is dealing with out-of-date content. This content clogs up websites, making it harder for users to find what is truly useful. Although the logical choice is to remove obsolete content, this can prove harder than it would appear. Many content owners become possessive about their content, arguing that somebody might find it useful. Suggestions of removing content can often be perceived as a personal attack on the content provider.

Having a predefined policy takes a lot of the contentiousness out of removing content. Instead of it being a personal attack, it is simply implementing policy. For example, you could have a policy that says if a page hasn’t be updated for a certain amount of time, it is automatically removed. Or you could specify that if a page falls below a certain threshold of visitors, it is removed from the website’s navigation or search. Whatever your policy, the key is to have something that can be implemented without endless discussion and debate.

Development Roadmap

The final policy that all organizations should definitely have is a development roadmap. This provides two benefits:

  • It prevents knee-jerk decision making about the next thing to implement.
  • It encourages management to think about ongoing development of their website, rather than occasional redesigns.

When talking about the fast moving world of digital development, it is not realistic to have a long-term, detailed roadmap. However, it should be possible to outline a list of ideas for future features, and prioritize those ideas based on your business objectives. Your roadmap should also outline a process for cyclic, ongoing improvements to the website. These aren’t necessarily new features, but rather usability enhancements based on monitoring of analytics and regular usability testing.

In his book “Rocket Surgery Made Easy,” Steve Krug recommends monthly lightweight usability testing to ensure that your website remains as usable as possible. This is very important, especially if your website is regularly having new content and features added. I understand that a post about roles, responsibilities and policies isn’t the most exciting topic. I get that most of us would prefer to play with the latest new jQuery plugin or responsive design technique.

The problem is that if we don’t start encouraging our clients and managers to think about these issues, the beautiful websites we create will quickly become bloated, neglected and ineffective. I am sure you do not consider this a part of your job, but if not you, then who? Personally, I am fed up with seeing websites I have created fall into disrepair and I will do whatever it takes to stop this from happening again. I hope you will join me.

(cp)


© Paul Boag for Smashing Magazine, 2012.


Design Language: The Organic Ambigram


  

The ambigram is one of the few modern letterforms that engage both your intellect and intuition simultaneously. It reads as a word while also communicating a deeply familiar pattern. This is something beyond the ambigram’s obviously clever construction. I’ve thought quite a bit about why I love this word-image hybrid, and I’ll set out here to uncover just what it is about the ambigram’s design and structure that makes it so captivating.

Design Is Alchemy
By combining eternal form with the fire of inspiration, you create something that did not exist before. This ambigram has two-point rotation symmetry. (Designer: Nikita Prokhorov)

My primary design background is as a symbolic logo designer, so I begin with what I know: symbols. I look to nature to create my work as a matter of practicality as well as aesthetics, because symbols are derived from nature and are the first language of all humans. Symbols engage us deeply as expressions of the organic principles and forms that life embodies. Nature is common to everyone, and when it is used symbolically in visual language, the chance of creating a relationship with the audience is significantly elevated because it mirrors the relationships within and around us. Nature even embeds symbols that mirror universal processes directly in our DNA.

The twisting double helix is a perfect example of opposites being combined into the genetic dance of balance that results in you and me. Unlike spoken or written language, natural symbols don’t have to be learned because we know them at our core. They are us.

Double Helix
Micro to macro, a handful of patterns construct everything in the universe. The weaving pattern of the helix combines two opposites in cooperation, the basis of organic life. (DNA micrograph: Andrzej Stasiak.) On the left, a double helix nebula at the center of the Milky Way galaxy. (Image: NASA.)

Art or design that incorporates natural symbolism resonates intuitively well before the intellect “makes sense� of it. Written language is processed intellectually first, before it is understood as images or emotions. Without a doubt, much of the ambigram’s appeal to me has to do with my preference for visual information, which you may share. But it is more universal than that.

An ambigram combines a word with the symbolic representation of a much larger principle. When you see reflection, oscillation, rotation, continuity and other universal principles integrated as an intrinsic part of a design, it engages you at a deep level. Any piece of art or design that embeds a universal principle is connected to something more, something real, something we just know.

Paris Ambigram
The Paris ambigram and logo has reflected (or mirror) symmetry. (Designer: Nikita Prokhorov)

Chain Reaction
“Chain Reaction� displays weaving, continuity and rotational symmetry. (Designer: John Langdon)

An ambigram takes on the same sort of life that a symbol does by connecting to nature, but how does it become its own entity, and such a visually lively one at that? To uncover this, we need to look at both parts of the ambigram: the word and the universal principle being expressed. Although the written word is the most apparent component of the ambigram, you intuitively process visual information before intellectually understanding it, so let’s start with image and intuition first.

Symbol-Speak

Humans have survived and proliferated by reading the universal principles and forms of nature as a common symbolic language, no matter when or where they have lived. The principles that constitute an effective ambigram resonate to your depths because you are made up of the very same fundamental formulas.

Your intuition knows that a circle is the shape of wholeness or completion (planets, eggs, cells, molecules, seasonal cycles); that waves oscillate to balance extremes (atoms and galaxies do this, too); that the branch pattern (tree branches, veins, lightning or the network of nerves that drive impulses throughout your body) moves life’s energy from one place to another; and that mirrored halves contain bilateral symmetry (the basic structural form of almost all higher animals, including humans).

When a universal principle becomes a primary ingredient in a piece of communication, be it literal or visual, something tells us to take note. The ambigram resembles independent, self-animated “life� by presenting the very same qualities.

Anatomy Snake
As the dominant symmetry in all higher life forms, bilateral symmetry is a compelling and intuitively recognizable principle. (Human anatomy image: Visual Language. Snake skeleton image: Srdjan Draskovic.)

Communication in the modern world has ramped up to a scale and speed never before possible, and the human species is now networked in the extreme. The Web connects the body of the world just as impulses connect throughout your body — but with one important difference: common ground must be established in human communication because of the many cultural and linguistic crossovers, unlike the immediate language of nature. Symbols help us do this by bringing an underlying fluency to people of different cultures and languages.

Symbols predate written language by at least tens of thousands of years and are far older than civilization itself. But because three-dimensional space is continually morphing, time erases nearly all traces. From what has been found to date (there is evidence of complex symbolic behavior going back as far as 200,000 to 500,000 years!), we know that our predecessors recognized the value of the information contained in natural patterns and forms all around us.

Snake Art
This six-meter-long python, discovered in Africa in 2006, is embellished with more than 300 manmade “scales� and is approximately 70,000 years old. Humans have been using their brains symbolically since “time out of mind.� (Image: Sheila Dawn Coulson)

All cultures use the same shapes and patterns in their art because we all experience them in the same way. Everything we’ve ever invented has come from understanding a universal underlying process and then replicating it as a human system. City grids mimic the stacking and packing patterns of nature in a linear format; apartment buildings and shopping carts contain the same pattern of stored energy in three dimensions; and road systems that carry petro-fueled vehicles mimic veins that carry the energy to fuel our bodies.

Patterns, shapes and processes of the natural world cue our inspiration and understanding by revealing the eternal baseline of existence. You simply can’t stop noticing nature’s processes in your peripheral vision. As constants of organic structure, they present an interesting paradox: the workings of nature are typically dismissed by our sped-up intellect as being commonplace but are recognized instantly by the senses as being essential and eternal.

Energetic Patterns
Nature’s process dictates effective human design. Packing and stacking is another natural pattern that efficiently stores energy that isn’t needed at the moment but is readily accessible. (Designer: John Langdon)

Language barriers preclude this ability to communicate universally and immediately. Visuals are immediate because they connect as a gestalt, and they communicate in both universally and personally relevant ways. The ambigram communicates more than the sum of its characters because it is enhanced with principles that communicate beyond the word itself.

The Manipulated and the Manipulator

Words, as opposed to symbols, tend towards specifics (different words can describe multiple aspects of one thing) and can dissect meaning into smaller and smaller details. Words are particularly good at giving directions, stating rules or declaring a law. Being created by humans, they are also malleable by humans. The way they are written can change lives, as is so often demonstrated in organized religion, law and politics. Written language is an essential human construct that not only provides information with efficient and (sometimes) consistent delivery, but allows generations to communicate their stories over time.

The Sun Microsystem
The Sun Microsystems logo has four-point rotational symmetry that emanates from the subset rotation of individual character sets — a vortex of self-similarity that contributes to the optical illusion of spinning. (Designer: Vaughan Pratt)

The ambigram is a perfect example of inclusiveness — and the root of the word tells you so up front. The word “ambigramâ€� is derived from two Latin words joined as one, as are many modern words. The root ambi means “both,â€� and it is a popular prefix in a world of dualities: day/night, youth/age, left/right, birth/death, good/evil — words that serve as the bounding markers of every human experience. Its suffix gram is another Latin word meaning tracing, mark, drawing, writing or record — a common suffix in our vocabulary ever since humans started taking notes. All sorts of everyday words include the prefix “ambiâ€� to connote “allâ€� or “inclusiveness.â€�

Illuminati
John Langdon created ambigrams for the films The Da Vinci Code and Angels and Demons, based on the books by Dan Brown. The perfect interplay of opposites is expressed in the rotational symmetry of “Angels and Demons� as equivalent extremes, while the single word “Illuminati� as the same word right side up or upside down alludes to its mystical and conspiratory nature.

Amb-ient is combined with the Latin -ier which means “to goâ€�. It is conjugated as an adjective with the -ient suffix to describe an overall relaxed mood (ambi, in this case, includes everything within extremes to surround you with an overall sensual feeling of balance and well being). Another word used in this context is ambition, or the act of moving around and through the multitudes — originally from a Latin word for “canvassing for votes,â€� and covering every base to reap the best return. The legal term “ambitâ€� is derived from the Latin ambitus, meaning scope, limits, boundary or circumference: the “ambit of a statute,â€� or “within the ambit of the law,â€� falls within legally defined bounds. Ambidextrous refers to both hands having equal dexterity. The Latin dexter means right — so, two rights for those who are adept at using both hands (the lefties might have a say about that). To be “ambivalentâ€� is to literally have either or both of two contrary or parallel values, qualities or meanings (the Latin verb -valeo means “to have valueâ€�). By its very nature, ambi is inclusive of opposites and implies wholeness.

The Infinity Circle
Called a “chain� ambigram, this design by Scott Kim presents an infinite loop that mimics the underlying cyclical motion of life and death.

A Living Loop

The ambigram’s sublime evolution exists within the form of the word itself. The word must have visual relationships to be interesting and relevant — not only in the way the characters create a meaningful word, but also in the symmetrical relationships that let you know you are experiencing something beyond just a simple word. It has the rather fantastic ability to be read upside down or backwards — and even sometimes in a loop!

Ambigrams mimic life by visually expressing some of the most basic principles that make up the entirety of living organic nature. There is one basic that underscores all of the different symmetries and structures that an ambigram can take on, and that is balance. In any beautiful and functioning design — manmade or natural — balance reigns supreme. Modern culture could learn from this: the opposite sides of your brain are not meant to contradict each other and entangle without resolution. Being creative is not of more or less value than being strategic. They are meant to work together. The same goes for opposite sides of the world’s hemispheres. When opposites combine in cooperation, they create something new, something useful, something beautiful that is far stronger and more resilient than is achieved by favoring one over another.

The Milky Way
Visible beyond towers of sedimentary rock, called “hoodoos,� in Bryce Canyon are thousands of individually discernible stars in the nearby Milky Way galaxy. (Image: Ben Cooper)

Despite the rather incredible technological advances made by humanity in the current era, we still lag behind our ancestors in understanding an important lesson displayed by the simple ambigram. We are nature and cannot put ourselves above our source, nor can we distance ourselves from it for very long. When you see a piece of design that simply makes you feel good, what you’re really seeing is an expression of nature flowing in place. It feels right because the common denominators that underscore all of life are the truest part of the human experience. It’s the most compelling reason there is. Ambigrams are closed living loops, little word ecosystems that stand independently on their own, just as each of us is designed to do.

(jc al)


© Maggie Macnab for Smashing Magazine, 2012.


How To Create An Embeddable Content Plugin For WordPress


  

WordPress is one of the most deployed content management systems around. One of the main reasons is the number of plugins available and the ease with which we can use the system. It is not uncommon to find websites using tens of plugins to accomplish various tasks and functions. Wouldn’t it be nice if you could share the site content with other websites?

You may have a need to share advertisements, product information or your photo gallery if you are a designer. Whatever the reason, this article will show you how to create an embeddable content plugin to share your WordPress content with other websites.

Share WordPress content via widgets.

Ways Of Sharing Content

There are various ways with which one can share content across websites — RSS and Atom feeds, APIs and embeddable widgets. RSS feeds on WordPress are usually restricted to posts, while APIs are not easy to integrate on other websites without adding some extra code. This leaves us with embeddable widgets — like the ones used by Google AdSense to display advertisements on websites or Facebook “Share” and “Like” buttons — all of these rely on embeddable JavaScript code to display specific content on a website. The idea mentioned in this article is certainly not new, but in the context of WordPress it opens up many possibilities. The advantages of the technique mentioned here compared with others is that it will enable you to share almost any content, even content from other plugins on your blog, with other websites.

Our goal in this article is to create widget code that a user could insert in their website to display a list of recent posts from the parent website. Of course, this can also be easily accomplished using RSS, but this is just an example to show the technique. In reality, you would use it for more interesting purposes, like sharing popular product images if you are running a WordPress e-commerce website.

The Widget Code

The embeddable code will look something like the following. This is the code the user will insert into their webpage, which will allow them to display the content from the parent website. The crucial element of this widget is the wp-widget.js file, which calls the remote WordPress website, gets the content and embeds it as an iframe in the calling page.

<script type="text/javascript">
  var widget_embed = 'posts';
</script>
<script src="http://www.example.com/widget/wp-widget.js"
type="text/javascript">
</script>
<div id="embed-widget-container"></div>

Adding this block of code to any website page will display the list of recent posts from example.com. The content can be anything besides posts — images, comments, tags, data from other plugins — anything you as a WordPress website owner would like to share with other people. For this example, I’ve limited the content to a simple posts list, as this is a common denominator across all WordPress websites and will be easy to start with. Of course, you will need to add some extra code to share other content, but the base plugin skeleton will remain the same.

Creating The Plugin

The fist step in creating an embeddable widget is to design a small WordPress plugin that will intercept the widget calls from another website and return the required data. You may be thinking that this will be a knotty job, but nothing could be easier. Just a few lines of code and our plugin is ready. The complete code for the plugin is shown below. I’ll explain how this works as we proceed along.

To get the content from the plugin, we will need to pass a query parameter of what content we would like from the remote server in the em_embed variable. This query parameter will then be intercepted by the plugin and the corresponding content returned. We will also pass along implicitly the domain URL of the calling page, so we can later use it for analytics purposes or for restricting the websites which can embed our widget.

For example, to get the list of recent posts, we need to send a GET query to the main WordPress website as shown below. Of course this query will be created by our JavaScript widget, wp-widget.js.


http://www.example.com/?em_embed=posts

The complete code for the plugin is given below.

<?php

/**
 * Plugin Name: WordPress Widget Embed
 * Description: Allow people to embed WordPress content in an iframe on other websites
 * Version: 1.0
 * Author: Sameer Borate
 * Author URI: http://www.codediesel.com
 */

class WPWidgetEmbed  
{
    public function __construct()
    {
        add_action('template_redirect', array($this, 'catch_widget_query'));
        add_action('init', array($this, 'widget_add_vars'));
    }
    
    /**
     * Adds our widget query variable to WordPress $vars
     */
    public function widget_add_vars() 
    { 
        global $wp; 
        $wp->add_query_var('em_embed'); 
        $wp->add_query_var('em_domain'); 
    }
    
    private function export_posts()
    {
        $outstring  = '<html>';
        $outstring .= '<head><style>';
        $outstring .= 'ul {
                padding:0;
                margin:0;
              }
              li {
                 list-style-type:none;
               }';
        $outstring .= '</style></head><body>';
         
        /* Here we get recent posts for the blog */
        $args = array(
            'numberposts' => 6,
            'offset' => 0,
            'category' => 0,
            'orderby' => 'post_date',
            'order' => 'DESC',
            'post_type' => 'post',
            'post_status' => 'publish',
            'suppress_filters' => true
        );
        
        $recent_posts = wp_get_recent_posts($args);
        
        $outstring .= '<div class="widget-posts"><ul>';
        foreach($recent_posts as $recent)
        {
            $outstring .= '<li><a target="_blank" href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"]. '</a></li>';
        }
        
        $outstring .= '</ul></div>';
        $outstring .= '</body></html>';
        
        return $outstring;
    }

    /**
     * Catches our query variable. If it's there, we'll stop the
     * rest of WordPress from loading and do our thing, whatever 
     * that may be. 
     */
    public function catch_widget_query()
    {
        /* If no 'embed' parameter found, return */
        if(!get_query_var('em_embed')) return;
        
        /* 'embed' variable is set, export any content you like */
        
        if(get_query_var('em_embed') == 'posts')
        { 
            $data_to_embed = $this->export_posts();
            echo $data_to_embed;
        }
        
        exit();
    }
}
 
$widget = new WPWidgetEmbed();

?>

To successfully intercept calls from another website, we need to first add the em_embed and em_domain parameters to our WordPress query_var variable. This will be used later to see what kind of data needs to be sent to the remote website. This is done by the following function.

public function widget_add_vars() 
{ 
    global $wp; 
    $wp->add_query_var('em_embed'); 
    $wp->add_query_var('em_domain');
}

Next, we will need to catch the query variable on the template_redirect hook and process any data if the em_embed variable is set in the global variable.

public function catch_widget_query()
{
    /* If no 'embed' parameter found, return */
    if(!get_query_var('em_embed')) return;
    
    /* 'embed' variable is set, export any content you like */
    
    if(get_query_var('em_embed') == 'posts')
    { 
        $data_to_embed = $this->export_posts();
        echo $data_to_embed;
    }
    
    exit();
}

In our example, we will be exporting a list of recent post titles, so our export_posts function will look like below.

private function export_posts()
{
    $outstring  = '<html>';
    $outstring .= '<head><style>';
    $outstring .= 'ul {
             padding-left:10px;
             margin:0;
          }
          
          li > a {
             text-decoration: none;
             font-family: Arial, Helvetica, Sans-serif;
             font-size:12px;
             
          }
           
          li {
             border-bottom: 1px solid #c0c0c0;
             padding: 3px 0 3px 0;
          }
    
          .widget-posts {
             width: 250px;
             border: 1px solid #c0c0c0;
             padding: 12px;
             margin-left: 3px;
          }';
    $outstring .= '</style></head><body>';
     
    /* Here we get recent posts for the blog */
    $args = array(
        'numberposts' => 6,
        'offset' => 0,
        'category' => 0,
        'orderby' => 'post_date',
        'order' => 'DESC',
        'post_type' => 'post',
        'post_status' => 'publish',
        'suppress_filters' => true
    );
    
    $recent_posts = wp_get_recent_posts($args);
    
    $outstring .= '<div id="widget-posts"><ul>';
    foreach($recent_posts as $recent)
    {
        $outstring .= '<li><a target="_blank" href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"]. '</a></li>';
    }
    
    $outstring .= '</ul></div>';
    $outstring .= '</body></html>';
    
    return $outstring;
}

This is all there is to the plugin. If you need to export any other data, you will need to replace the code for getting posts with code for getting the data you like.

Writing The Embeddable Widget Code

We have now completed only the part for the WordPress plugin. We still have to write the JavaScript embed code which will remotely access our website and insert the appropriate content into the calling page. The easiest way to display content from another website into your Web page is by using an iframe. The code needed to embed the content on a website is shown below.

<script type="text/javascript">
  var widget_embed = 'posts';
</script>
<script src="http://www.example.com/widget/wp-widget.js"
type="text/javascript">
</script>
<div id="embed-widget-container"></div>

If you are going to use the widget for returning only a single type of data,you can do away with the widget_embed variable. So you will have something like the following.

<script src="http://www.example.com/widget/wp-widget.js"
type="text/javascript">
</script>
<div id="embed-widget-container"></div>

wp-widget.js is the JavaScript that does all the work of calling the remote WordPress website and adding the content to the iframe. You need to place the wp-widget.js file in a subdirectory on your WordPress website; the exact name and location does not matter.

The complete code for the wp-widget.js is shown below, and is self-explanatory.

/**
  * wp-widget.js
  *
  * Inserts an iframe into the DOM and calls the remote embed plugin
  * via a get parameter:
  * e.g http://www.example.com/?embed=posts
  * This is intercepted by the remote 'WordPress Widget Embed' plugin
  *
  */

(function() {

// Localize jQuery variable
var jQuery;

/* Load jQuery if not present */
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.7.2') 
{
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
    if (script_tag.readyState) 
    {
      script_tag.onreadystatechange = function () 
      { // For old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') 
          {
              scriptLoadHandler();
          }
      };
    } 
    else 
    {
      script_tag.onload = scriptLoadHandler;
    }
    
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} 
else 
{
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}


/* Called once jQuery has loaded */
function scriptLoadHandler() 
{
    jQuery = window.jQuery.noConflict(true);
    main(); 
}

/* Our Start function */
function main() 
{ 
    jQuery(document).ready(function($) 
    { 
        /* Get 'embed' parameter from the query */
        var widget = window.widget_embed;
        var domain = encodeURIComponent(window.document.location);
    
        /* Set 'height' and 'width' according to the content type */
        var iframeContent = '<iframe style="overflow-y: hidden;" \
                             height="550" width="400" frameborder="0" \
                             border="0" cellspacing="0" scrolling="no" \
                             src="http://www.example.com/?em_embed=' + widget + '&em_domain=' + domain + '"></iframe>';
                             
        $("#embed-widget-container").html(iframeContent);
    });
}

})();

The task of inserting the iframe and the WordPress content in the DOM is accomplished by the main() function. The iframe size needs to be changed depending on your requirements or created dynamically by letting the user pass additional parameters along with the widget_embed variable in the main widget code.

Adding Custom CSS To The Content

You can also add custom CSS to the displayed content through the plugin. Sample CSS to go with the above plugin is given below. You can also specify a style sheet URL if needed.

private function export_posts()
{
    $outstring  = '<html>';
    $outstring .= '<head><style>';
    $outstring .= 'ul {
             padding-left:10px;
             margin:0;
          }
          
          li > a {
             text-decoration: none;
             font-family: Arial, Helvetica, Sans-serif;
             font-size:12px;
          }
           
          li {
             border-bottom: 1px solid #c0c0c0;
             padding: 3px 0 3px 0;
          }
          
          .widget-posts {
             width: 250px;
             border: 1px solid #c0c0c0;
             padding: 12px;
             margin-left: 3px;
          }';
    $outstring .= '</style></head><body>';
    .
    .

The type of CSS you add to the content will depend on what content you are displaying. With a little creative coding, you can also allow the user to add certain display options to the widget with which they can control the display style of the embedded widget.

Restricting Display To Certain Domains

You may want to allow only certain domains to be able to display your content using the widget. This can easily be made possible, as we already have the calling website’s url in the em_domain variable. All we have to do is check the domain and selectively allow the content to be displayed.

public function catch_widget_query()
{
    /* If no 'embed' parameter found, return */
    if(!get_query_var('em_embed')) return;
    
    /* 'embed' variable is set, export any content you like */
    
    if(get_query_var('em_embed') == 'posts')
    { 
        $allowed_domains = array('site1.com',
                                 'site2.com',
                                 'site3.com');
                                 
        $calling_host = parse_url(get_query_var('em_domain'));
        
        /* Check if the calling domain is in the allowed domains list */
        if(in_array($calling_host['host'], $allowed_domains))
        {
            $data_to_embed = $this->export_posts();
            echo $data_to_embed;
        }
        else
        {
            echo "Domain not registered!";
        }
    }
    
    exit();
}

Performance Concerns

Allowing other websites to access your content via widgets means additional load on your servers. A few hundred websites using your widget could easily slow down your server, so take this factor into consideration when promoting widgets. However, plugins like WP Super Cache can be used to cache widget data and reduce server load. If you are not using WP Super Cache or any other cache plugin, you can try using the WordPress Transients API to save the results into the database.

The WordPress Transients API offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a time frame, after which it will expire and be deleted. The catch_widget_query() function after adding the WP Transient API code is shown below.

public function catch_widget_query()
{
    /* If no 'embed' parameter found, return */
    if(!get_query_var('em_embed')) return;
    
    /* 'embed' variable is set, export any content you like */
    
    if(get_query_var('em_embed') == 'posts')
    { 
        /* Here we are now using the 'WP Transient API'. 
           See if we have any saved data for the 'ewidget' key.
         */
        $cached = get_transient('ewidget');
        
        /* Oops!, the cache is empty */
        if(empty($cached))
        {
            /* Get some fresh data */
            $data_to_embed = $this->export_posts();
            
            /* Save it using the 'WP Transient API' using the 'ewidget' key,
               set it to expire after 12 hours.
             */
            set_transient('ewidget', $data_to_embed, 60 * 60 * 12);
            echo $data_to_embed;
        }
        /* Yes we found some, so we return that to the user */
        else
        {
            echo $cached;
        }
    }
    
    exit();
}

In Conclusion

Sharing your content across different websites is a nice way to market your services and create brand awareness. With millions of WordPress websites around, there is a huge amount of content out there that can be profitably shared among users. Not just text, but also images, videos, advertisements, etc. This article is just a simple implementation of an embeddable widget. You can customize it in various ways to include security, analytics code to track widget usage and other functionality.

(cp)


© Sameer Borate for Smashing Magazine, 2012.


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress