Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

May 15 2013

07:00

I am a coding denier

There is an exchange that sometimes takes place, perfectly described by Beth Ashton, between those who use technology, and those who don’t. It goes like this:

Prospective data journalist: ‘I’d really like to learn how to do data journalism but I can’t do statistics!’

Data journalist: ‘Don’t let that put you off, I don’t know anything about numbers either, I’m a journalist, not a mathematician!’

Prospective data journalist: ‘But I can’t code, and it all looks so codey and complicated’

Data journalist: That’s fine, NONE OF US can code. None of us. Open angle bracket back slash End close angle bracket.

“These people are coding deniers,” argues Beth.

I think she’s on to something. Flash back to a week before Beth published that post: I was talking to Caroline Beavon about the realisation of just how hard-baked ‘coding’ was into my workflow:

  • A basic understanding of RSS lies behind my ability to get regular updates from hundreds of sources
  • I look at repetitiveness in my work and seek to automate it where I can
  • I look at structure in information and use that to save time in accessing it

These are all logical responses to an environment with more information than a journalist can reasonably deal with, and I have developed many of them almost without realising.

They are responses as logical as deciding to use a pen to record information when human memory cannot store it reliably alone. Or deciding to learn shorthand when longhand writing cannot record reliably alone. Or deciding to use an audio recorder when that technology became available.

One of the things that makes us uniquely human is that we reach for technological supports – tools – to do our jobs better. The alphabet, of course, is a technology too.

But we do not argue that shorthand comes easy, or that audio recorders can be time consuming, or that learning to use a pen takes time.

So: ‘coding’ – whether you call it RSS, or automation, or pattern recognition – needs to be learned. It might seem invisible to those of us who’ve built our work patterns around it – just as the alphabet seems invisible once you’ve learned it. But, like the alphabet, it is a technology all the same.

But secondly – and more importantly – for this to happen as a profession we need to acknowledge that ‘coding’ is a skill that has become as central to working effectively in journalism as using shorthand, the pen, or the alphabet.

I don’t say ‘will be central’ but ‘has become‘. There is too much information, moving too fast, to continue to work with the old tools alone. From social networks to the quantified self; from RSS-enabled blogs to the open data movement; from facial recognition to verification, our old tools won’t do.

So I’m not going to be a coding denier. Coding is to digital information what shorthand was to spoken information. There, I’ve said it. Now, how can we do it better?

07:00

I am a coding denier

There is an exchange that sometimes takes place, perfectly described by Beth Ashton, between those who use technology, and those who don’t. It goes like this:

Prospective data journalist: ‘I’d really like to learn how to do data journalism but I can’t do statistics!’

Data journalist: ‘Don’t let that put you off, I don’t know anything about numbers either, I’m a journalist, not a mathematician!’

Prospective data journalist: ‘But I can’t code, and it all looks so codey and complicated’

Data journalist: That’s fine, NONE OF US can code. None of us. Open angle bracket back slash End close angle bracket.

“These people are coding deniers,” argues Beth.

I think she’s on to something. Flash back to a week before Beth published that post: I was talking to Caroline Beavon about the realisation of just how hard-baked ‘coding’ was into my workflow:

  • A basic understanding of RSS lies behind my ability to get regular updates from hundreds of sources
  • I look at repetitiveness in my work and seek to automate it where I can
  • I look at structure in information and use that to save time in accessing it

These are all logical responses to an environment with more information than a journalist can reasonably deal with, and I have developed many of them almost without realising.

They are responses as logical as deciding to use a pen to record information when human memory cannot store it reliably alone. Or deciding to learn shorthand when longhand writing cannot record reliably alone. Or deciding to use an audio recorder when that technology became available.

One of the things that makes us uniquely human is that we reach for technological supports – tools – to do our jobs better. The alphabet, of course, is a technology too.

But we do not argue that shorthand comes easy, or that audio recorders can be time consuming, or that learning to use a pen takes time.

So: ‘coding’ – whether you call it RSS, or automation, or pattern recognition – needs to be learned. It might seem invisible to those of us who’ve built our work patterns around it – just as the alphabet seems invisible once you’ve learned it. But, like the alphabet, it is a technology all the same.

But secondly – and more importantly – for this to happen as a profession we need to acknowledge that ‘coding’ is a skill that has become as central to working effectively in journalism as using shorthand, the pen, or the alphabet.

I don’t say ‘will be central’ but ‘has become‘. There is too much information, moving too fast, to continue to work with the old tools alone. From social networks to the quantified self; from RSS-enabled blogs to the open data movement; from facial recognition to verification, our old tools won’t do.

So I’m not going to be a coding denier. Coding is to digital information what shorthand was to spoken information. There, I’ve said it. Now, how can we do it better?

September 05 2012

15:39

Miranda Mulligan: Want to produce hirable grads, journalism schools? Teach them to code

Editor’s Note: It’s the start of the school year, which means students are returning to journalism programs around the country. As the media industry continues to evolve, how well is new talent being trained, and how well are schools preparing them for the real world?

We asked an array of people — hiring editors, recent graduates, professors, technologists, deans — to evaluate the job j-schools are doing and to offer ideas for how they might improve. Over the coming days, we’ll be sharing their thoughts with you. Here’s Miranda Mulligan — new executive director of the Knight News Innovation Lab at Northwestern, formerly digital design director for The Boston Globe — arguing that journalists need to learn how to code if they want to become better (and employable) storytellers.

Learning how to make software for storytelling and how to realize news presentations into code are currently the hottest, most pressing skillsets journalists can study. There has never before been more urgency for our industry to understand enough code to have meaningful conversations with technologists.

And yet if you attend any event with a collection of jouro-nerd types, inevitably the same question will come up. Someone will ask — philosophically, of course — “How can we tell better stories on the web?” and proceed to bemoan the tedium of reading a daily newspaper and a newspaper website, likening it to Groundhog Day, the same stories presented the same way, day after day. Sooner or later others add their frustrations that “we” — in 2012 — are still writing for the front page instead of the homepage.

It is our job as educators to remove fear of learning, a fear notoriously prevalent in journalists.

We’ve all had this discussion a thousand times. But now, it’s not just the visual journalists complaining about the stagnation of online storytelling and presentation.

For me, there’s only one response to this: Journalists should learn more about code. Understanding our medium makes us better storytellers. For an industry that prides itself on being smart, tolerating ignorance of the Internet is just stupid.

The time is now for our future journalists to learn about code. We need to innovate our curricula, really looking at what we are teaching our students. Learning, or mastering, specific software is not properly preparing our future journalists for successful, life-long careers. No one can learn digital storytelling in a semester. Mastering Dreamweaver and Flash isn’t very future-friendly, and having a single mid-level “Online Journalism” course offered as an elective does more harm than good. We should be teaching code in all of our journalism courses — each semester, each year, until graduation.

The list of jobs for designers and journalists who can write code is growing — seemingly exponentially. So, let’s all grab our copies of The Art of War and attack this problem from every angle: We need to teach our students to be more technologically literate. We need to teach them how to learn and how to fail. That, my friends, is making the Internet.

I am not arguing that every single writer/editor/publisher who learns some programming should end up becoming a software engineer or a refined web designer. The end goal here is not programming fluency. However, there’s a lot of value in understanding how browsers read and render our stories. Reporting and writing a story, writing some code (HTML, CSS, Javascript), and programming complex applications and services are all collections of skills. A fundamental knowledge of code allows for:

  • More significant conversations about digital presentation, ultimately leading to better, more meaningful, online storytelling. Understanding your medium makes you better at your craft.
  • Deeper thought and understanding of data. Learning more about what goes into writing and programming software teaches you to think in terms of abstractions, functions, parameters, components, frameworks, object classes, templates, and more.

Journalism needs hirable graduates that can create sophisticated visual presentations and can realize them in code. But many students are intimidated, not excited, by the tools now fundamental to visual storytelling. In fact, the prevailing sentiment throughout journalism and communications specialties is that “we” are still intimidated. Maybe this attitude is trickling down to the universities — or maybe up from them. But “we” have all got to get over our fear of the Internet.

Last September, I participated in a half-day student seminar at the Society of News Design’s annual workshop in St. Louis. To be brazen and speak for my panel-mates, we were all shocked by how apprehensive the students were toward HTML, CSS, and Javascript. In fact, after three hours of nudging them to make the time to learn some code, a female student boldly asserted that she really didn’t care about digital design and wanted advice for students hoping to break into print design.

It’s our job as educators to remove fear of learning, a fear notoriously prevalent in journalists. HTML is not magic. Writing code is not wizardry; it’s just hard work. Learning to program will not save journalism and probably won’t change the way we write our stories. It is, however, a heck of a lot more fun being a journalist on the web once “how computers read and understand our content” is understood.

Learning to program not only provides a practical skill — it also teaches problem solving. Students are learning more precise and nuanced thought processes, and the depth of their understanding of information and data will only grow. Also, for visual journalists, teaching code is teaching information design. Both news designers and web designers are burdened with the same responsibilities: organizing and rationally arranging content, illustrating ideas to deepen the understanding of a story, and working within the constraints of the medium.

I believe the most important thing an instructor can ever do is inspire students to be open-minded about their skills. No one knows what the storytelling landscape will look like in two years, let alone a decade from now. As educators, we can make becoming a digital journalist feel accessible and attainable. Graduates should leave armed with a skillset that includes the ability to learn quickly and adapt, to be open to new ideas and solutions, and to take initiative like the self-starters they were born to become. They will never get bored, and they will always be employable.

Our journalism pedagogy should inspire future digital journalists to be Internauts, to continually grow, constantly teaching themselves the newest storytelling tools and techniques, instilling processes for life-long learning.

Image by Steve Rhode used under a Creative Commons license.

December 08 2011

17:27

Daily Must Reads, Dec. 8, 2011

The best stories across the web on media and technology


1. The choice of BBM over Twitter in the recent UK riots illustrates social stratification (Guardian)

2. New businesses pop up to teach web programming (Wall Street Journal)

3. How Twitter's trending algorithm picks its topics (NPR)

4. 70% of Americans have no idea what geolocation apps are (ReadWriteWeb)

5. David Goetzl: Email is the new social (MediaPost)




Subscribe to our daily Must Reads email newsletter and get the links in your in-box every weekday!



Subscribe to Daily Must Reads newsletter

This is a summary. Visit our site for the full post ».

August 03 2011

14:00

Transparency, iteration, standards: Knight-Mozilla’s learning lab offers journalism lessons of open source

This spring, the Knight Foundation and Mozilla took the premise of hacks and hackers collaboration and pushed it a step further, creating a contest to encourage journalists, developers, programmers, and anyone else so inclined to put together ideas to innovate news.

Informally called “MoJo,” the Knight-Mozilla News Technology Partnership has been run as a challenge, the ultimate prize being a one-year paid fellowship in one of five news organizations: Al Jazeera English, the BBC, the Guardian, Boston.com, and Zeit Online.

We’ve been following the challenge from contest entries to its second phase, an online learning lab, where some 60 participants were selected on the basis of their proposal to take part in four weeks of intense lectures. At the end, they were required to pitch a software prototype designed to make news, well, better.

Through the learning lab, we heard from a super cast of web experts, like Chris Heilmann, one of the guys behind the HTML5 effort; Aza Raskin, the person responsible for Firefox’s tabbed browsing; and John Resig, who basically invented the jQuery JavaScript library; among other tech luminaries. (See the full lineup.)

There was a theme running through the talks: openness. Not only were the lectures meant to get participants thinking about how to make their projects well-designed and up to web standards, but they also generally stressed the importance of open-source code. (“News should be universally accessible across phones, tablets, and computers,” MoJo’s site explains. “It should be multilingual. It should be rich with audio, video, and elegant data visualization. It should enlighten, inform, and entertain people, and it should make them part of the story. All of that work will be open source, and available for others to use and build upon.”)

We also heard from journalists: Discussing the opportunities and challenges for technology and journalism were, among other luminaries, Evan Hansen, editor-in-chief of Wired.com; Amanda Cox, graphics editor of The New York Times; Shazna Nessa, director of interactive at the AP; Mohamed Nanabhay, head of new media at Al Jazeera English; and Jeff Jarvis.

In other words, over the four weeks of the learning lab’s lectures, we heard from a great group of some of the smartest journalists and programmers who are thinking about — and designing — the future of news. So, after all that, what can we begin to see about the common threads emerging between the open source movement and journalism? What can open source teach journalism? And journalism open source?

Finding 1:
* Open source is about transparency.
* Journalism has traditionally not been about transparency, instead keeping projects under wraps — the art of making the sausage and then keeping it stored inside newsrooms.

Because open-source software development often occurs among widely distributed and mostly volunteer participants who tinker with the code ad-hoc, transparency is a must. Discussion threads, version histories, bug-tracking tools, and task lists lay bare the process underlying the development — what’s been done, who’s done it, and what yet needs tweaking. There’s a basic assumption of openness and collaboration achieving a greater good.

Ergo: In a participatory news world, can we journalists be challenged by the ethics of open source to make the sausage-making more visible, even collaborative?

No one is advocating making investigative reporting an open book, but sharing how journalists work might be a start. As Hansen pointed out, journalists are already swimming in information overload from the data they gather in reporting; why not make some of that more accessible to others? And giving people greater space for commenting and offering correction when they think journalists have gone wrong — therein lies another opportunity for transparency.

Finding 2:
* Open source is iterative.
* Journalism is iterative, but news organizations generally aren’t (yet).

Software development moves quickly. Particularly in the open source realm, developers aren’t afraid to make mistakes and make those mistakes public as they work through the bugs in a perpetual beta mode rather than wait until ideas are perfected. The group dynamic means that participants feel free to share ideas and try new things, with a “freedom to fail” attitude that emphasizes freedom much more than failure. Failure, in fact, is embraced as a step forward, a bug identified, rather than backward. This cyclical process of iterative software development — continuous improvement based on rapid testing — stands in contrast to the waterfall method of slower, more centralized planning and deployment.

On the one hand, journalism has iterative elements, like breaking news. As work, journalism is designed for agility. But journalism within legacy news organizations is often much harder to change, and tends to be more “waterfall” in orientation: The bureaucracy and business models and organizational structures can take a long time to adapt. Trying new things, being willing to fail (a lot) along the way, and being more iterative in general are something we can learn from open-source software.

Finding 3:
* Open source is about standards.
* So is journalism.

We were surprised to find that, despite its emphasis on openness and collaboration, the wide world of open source is also a codified world with strict standards for implementation and use. Programming languages have documentation for how they are used, and there is generally consensus among developers about what looks good on the web and what makes for good code.

Journalism is also about standards, though of a different kind: shared values about newsgathering, news judgment, and ethics. But even while journalism tends to get done within hierarchical organizations and open-source development doesn’t, journalism and open source share essentially the same ideals about making things that serve the public interest. In one case, it’s programming; in the other case, it’s telling stories. But there’s increasingly overlap between those two goals, and a common purpose that tends to rise above mere profit motive in favor of a broader sense of public good.

However, when it comes to standards, a big difference between the the open-source movement and journalism is that journalists, across the board, aren’t generally cooperating to achieve common goals. While programmers might work together to make a programming language easier to use, news organizations tend to go at their own development in isolation from each other. For example, The Times went about building its pay meter fairly secretly: While in development, even those in the newsroom didn’t know the details about the meter’s structure. Adopting a more open-source attitude could teach journalists, within news organizations and across them, to think more collaboratively when it comes to solving common industry problems.

Finding 4:
* Open-source development is collaborative, free, and flexible.
* Producing news costs money, and open source may not get to the heart of journalism’s business problems.

Open-source software development is premised on the idea of coders working together, for free, without seeking to make a profit at the expense of someone else’s intellectual property. Bit by bit, this labor is rewarded by the creation of sophisticated programming languages, better-and-better software, and the like.

But there’s a problem: Journalism can’t run on an open source model alone. Open source doesn’t give journalism any guidance for how to harness a business model that pays for the news. Maybe open-source projects are the kind of work that will keep people engaged in the news, thus bulking up traditional forms of subsidy, such as ad revenue. (Or, as in the case of the “open R&D” approach of open APIs, news organizations might use openness techniques to find new revenue opportunities. Maybe.)

Then again, the business model question isn’t, specifically, the point. The goal of MoJo’s learning lab, and the innovation challenge it’s part of, is simply to make the news better technologically — by making it more user-friendly, more participatory, etc. It’s not about helping news organizations succeed financially. In all, the MoJo project has been more about what open source can teach journalism, not vice versa. And that’s not surprising, given that the MoJo ethos has been about using open technologies to help reboot the news — rather than the reverse.

But as the 60 learning lab participants hone their final projects this week, in hopes of being one of the 15 who will win a next-stage invite to a hackathon in Berlin, they have been encouraged to collaborate with each other to fill out their skill set — by, say, a hack partnering with a hacker, and so forth. From those collaborations may come ideas not only for reinventing online journalism, but also for contributing to the iteration of open-source work as a whole.

So keep an eye out: Those final projects are due on Friday.

March 25 2011

11:25

OpenCorporates partners with ScraperWiki & offers bounties for open data scrapers

This is a guest post by Chris Taggart, co-founder of OpenCorporates

When we started OpenCorporates it was to solve a real need that we and a number of other people in the open data community had: whether it’s Government spending, subsidy info or court cases, we needed a database of corporate entities to match against, and not just for one country either.

But we knew from the first that we didn’t want this to be some heavily funded monolithic project that threw money at the project in order to create a walled garden of new URIs unrelated to existing identifiers. It’s also why we wanted to work with existing projects like OpenKvK, rather than trying to replace them.

So the question was, how do we make this scale, and at the same time do the right thing – that is work with a variety of different people using different solutions and different programming languages. The answer to both, it turns out, was to use open data, and the excellent ScraperWiki.

How does it work? Well, the basics we need in order to create a company record at OpenCorporates is the company number, the jurisdiction and the company’s name. (If there’s a status field — e.g. dissolved/active — company type or url for more data, that’s a bonus). So, all you need to do is write a scraper for a country we haven’t got data for, name the fields in a standard way (CompanyName, CompanyNumber, Status, EntityType, RegistryUrl, if the url of the company page can’t be worked out from the company number), and bingo, we can pull it into OpenCorporates, with just a couple of lines of code.

Let’s have a look at one we did earlier: the Isle of Man (there’s also one for GibraltarIreland, and in the US, the District of Columbia). It’s written in Ruby, because that’s what we at OpenCorporates code in, but ScraperWiki allows you to write scrapers in Python or php too, and the important thing here is the data, not the language used to produce it.

The Isle of Man company registry website is a .Net system which uses all sorts of hidden fields and other nonsense in the forms and navigation. This is a normally bit of a pain, but because you can use the Ruby Mechanize library to submit forms found on the pages (there’s even a tutorial scraper which shows how to do it), it becomes fairly straightforward.

The code itself should be fairly readable to anyone familiar with Ruby or Python, but essentially it tackles the problem by doing multiple searches for companies beginning with two letters, starting with ‘aa’ then ‘ab’ and so on, and for each letter pair iterating through each page of results in turn, which in turn is scraped to extract the data, using the standardised headings to save them in.  That’s it.

In the space of a couple of hours not only have we liberated the data, but both the code and the data are there for anyone else to use too, as well as being imported in OpenCorporates.

However, that’s not all. In order to kickstart the effort OpenCorporates (technically Chrinon Ltd, the micro start-up that’s behind OpenCorporates) is offering a bounty for new jurisdictions opened up.

It’s not huge (we’re a micro-startup remember): £100 for any jurisdiction that hasn’t been done yet, £250 for those territories we want to import sooner rather than later (Australia, France, Spain), and £500 for Delaware (there’s a captcha there, so not sure it’s even possible), and there’s an initial cap of £2500 on the bounty pot (details at the bottom of this post).

However, often the scrapers can be written in a couple of hours, and it’s worth stressing again that neither the code nor the data will belong to OpenCorporates, but to the open data community, and if people build other things on it, so much the better. Of course we think it would make sense for them to use the OpenCorporates URIs to make it easy to exchange data in a consistent and predictable way, but, hey, it’s open data ;-)

Small, simple pieces, loosely connected, to build something rather cool. So now you can do a search for, oh say Barclays, and get this:

The bounty details: how it works

Find a country/company registry that you fancy opening up the data for (here are a couple of lists of registries). Make sure it’s from the official registry, and not a commercial reseller. Check too that no-one has already written one, or is in the middle of writing one, by checking the scrapers tagged with opencorporates (be nice, and respect other people’s attempts, but feel free to start one if it looks as if someone’s given up on a scraper).

All clear? Go ahead and start a new scraper (useful tutorials here). Call it something like trial_fr_company_numbers (until it’s done and been OK’d) and get coding, using the headings detailed above for the CompanyNumber, CompanyName etc. When it’s done, and it’s churning away pulling in data, email us info@opencorporates.com, and assuming it’s OK, we’ll pay you by Paypal, or by bank transfer (you’ll need to give us an invoice in that case). If it’s not we’ll add comments to the scraper. Any questions, email us at info@opencorporates.com, and happy scraping.

January 08 2011

12:01

Is their any software on net where I can do this easily??

I am a accountant. I am preparing a balance sheet but because of staff shortage and time pressures I cant complete it on time. There is lot of common data with last years which I need not retype and I can manage by editing last year’s balance sheet ? Is their any software on net where I can do this easily??

Tags: coding

November 17 2010

20:05

What to use for lightweight bug/issue tracking?

What do people use for bug tracking? Ideally we'd want something super lightweight with as little of a learning curve as possible.

We use Google Docs occasionally, but would like something a little (just a little, mind you) less ad-hoc.

September 21 2010

13:09

Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Smashing-magazine-advertisement in Five Useful CSS/jQuery Coding Techniques For More Dynamic WebsitesSpacer in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites
 in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites  in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites  in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Interactivity can transform a dull static website into a dynamic tool that not only delights users but conveys information more effectively. In this post, we’ll walk through five different coding techniques that can be easily implemented on any website to provide a richer user experience.

The techniques will allow you to better display difficult content, help users find information more effectively and provide meaningful UI cues without overwhelming the user.

  1. On-page text search
  2. Drag controls for oversized content
  3. Subtle hover effects
  4. Comment count bars
  5. Full-page slider

[Offtopic: by the way, did you already get your copy of the Smashing Book?]

1. On-Page Text Search

E-read-search-instant in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Websites often have search boxes to allow users to find content from their archives. But what if you want to find content on the given page? Information Architects has had on-page text search that provides a great user experience. Let’s recreate this using jQuery.

Mark-Up and Interaction

First let’s build an input box for the search:

<input type="text" id="text-search" />

Next we’ll need jQuery to attach a listener to track changes to the input box:

$(function() {
    $('#text-search').bind('keyup change', function(ev) {
        // pull in the new value
        var searchTerm = $(this).val();
    )};
});

Here we bound our function to both the keyup and change events. This ensures that our operation fires regardless of whether the user types or pastes the text.

Now, let’s turn to Highlight, a useful and lightweight jQuery plug-in that handles text highlighting. After including the plug-in source, let’s add a highlight() call to our JavaScript:

$(function() {
    $('#text-search').bind('keyup change', function(ev) {
        // pull in the new value
        var searchTerm = $(this).val();

        // disable highlighting if empty
        if ( searchTerm ) {
            // highlight the new term
            $('body').highlight( searchTerm );
        }
    });
});

In addition to highlighting the given text, we’ve also added a check to make sure the search term isn’t empty (which causes an infinite loop).

This snippet highlights the search query throughout the page, but we can also limit the scope to a given id:

$('#myId').highlight( searchTerm );

Or we can search only within a certain element:

$('p').highlight( searchTerm );

This text highlighting by default is case insensitive. If you’d prefer case-sensitive highlighting, remove the .toUpperCase() on both lines 21 and 41 of the Highlight plug-in.

Styling the Highlighted Text

Now that the JavaScript is attached, we’ll need to style our highlighted items. The Highlight plug-in wraps the highlighted terms in <span class="highlight"></span>, which we can style with CSS.

First, let’s change the background color and then add rounded corners and a drop-shadow for all browsers except IE:

.highlight {
    background-color: #fff34d;
    -moz-border-radius: 5px; /* FF1+ */
    -webkit-border-radius: 5px; /* Saf3-4 */
    border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
    -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}

Although the highlighting is now visible, it still appears a bit tight around the text and could use some padding. But we’ll have to be careful not to adjust the layout of text. These spans are inline elements, and if we simply add padding, the text will shift around on the page. So, let’s include padding with a negative margin to compensate:

.highlight {
    padding:1px 4px;
    margin:0 -4px;
}

Finishing the Interaction

Last but not least, let’s make sure to remove the highlighted text whenever the user edits text in the input box:

$(function() {
    $('#text-search').bind('keyup change', function(ev) {
        // pull in the new value
        var searchTerm = $(this).val();

        // remove any old highlighted terms
        $('body').removeHighlight();

        // disable highlighting if empty
        if ( searchTerm ) {
            // highlight the new term
            $('body').highlight( searchTerm );
        }
    });
});

Here we added a call to remove any text highlighting, which is performed outside of the empty field check. This ensures that the highlight is also removed if the user clears the field.

Although removeHighlight() works well in most browsers, it will crash IE6. This is due to an IE6 bug with node.normalize().

We can get the Highlight plug-in working in IE6 by rewriting this function. Simply replace lines 45-53 of highlight.js with the following:

jQuery.fn.removeHighlight = function() {
 function newNormalize(node) {
    for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
        var child = children[i];
        if (child.nodeType == 1) {
            newNormalize(child);
            continue;
        }
        if (child.nodeType != 3) { continue; }
        var next = child.nextSibling;
        if (next == null || next.nodeType != 3) { continue; }
        var combined_text = child.nodeValue + next.nodeValue;
        new_node = node.ownerDocument.createTextNode(combined_text);
        node.insertBefore(new_node, child);
        node.removeChild(child);
        node.removeChild(next);
        i--;
        nodeCount--;
    }
 }

 return this.find("span.highlight").each(function() {
    var thisParent = this.parentNode;
    thisParent.replaceChild(this.firstChild, this);
    newNormalize(thisParent);
 }).end();
};

This new function replaces the standard Javascript normalize() with a custom function that works in all browsers.

Download the complete example.

2. Drag Controls For Oversized Content

Moscow in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

When layout constraints bump up against the need for large images, finding a quality solution can be difficult. Mospromstroy uses a creative technique to handle this situation: a "drag and drop" control bar that allows users to pan through images.

We can accomplish something similar using jQuery UI's draggable behavior.

Mark-Up and CSS

First let's set up some mark-up for the content and controls:

<div id="full-sized-area">
    <div id="full-sized-content">
    Your content here
    </div>
</div>

<div id="drag-controls-area">
    <div id="drag-controls"></div>
</div>

Next, let's apply some basic CSS:

#full-sized-area {
    position: relative;
    overflow: hidden;
    width: 800px;
    height: 400px;
}

#full-sized-content {
    position: absolute;
    top: 0;
    left: 0;
}

#drag-controls-area {
    position: relative;
    width: 300px;
    height: 50px;
}

#drag-controls {
    position: absolute;
    top: 0;
    left: 0;
    height: 48px;
    border: 1px solid white;
}

Here we applied an absolute position to both the #full-sized-content and #drag-controls, and we also hid any overflow from the large image. Additionally, we applied some arbitrary dimensions to the content and drag controls wrappers; make sure to adjust these as needed.

Building Interactivity With jQuery

Now, let's use jQuery UI to build the interaction. Begin by including jQuery UI with the draggable module.

Before attaching the controls, let's resize the drag control box to the right dimensions:

$(function() {
    var $fullArea = $('#full-sized-area');
    var $fullContent = $('#full-sized-content', $fullArea);

    // find what portion of the content is displayed
    var contentRatio = $fullArea.width() / $fullContent.width();

    // scale the controls box
    var $controlsArea = $('#drag-controls-area');
    var $controls = $('#drag-controls', $controlsArea);

    $controls.css('width', $controlsArea.width() * contentRatio);
});

Here, we've determined what portion of the content is visible in the content area and then scaled the width of the control box accordingly.

Next, let's attach the draggable behavior:

$(function() {
    var $fullArea = $('#full-sized-area');
    var $fullContent = $('#full-sized-content', $fullArea);

    // find what portion of the content is displayed
    var contentRatio = $fullArea.width() / $fullContent.width();

    // scale the controls box
    var $controlsArea = $('#drag-controls-area');
    var $controls = $('#drag-controls', $controlsArea);

    $controls.css('width', $controlsArea.width() * contentRatio);

    // determine the scale difference between the controls and content
    var scaleRatio = $controlsArea.width() / $fullContent.width();

    // attach the draggable behavior
    $controls.draggable({
        axis : 'x', // confine dragging to the x-axis
        containment : 'parent',
        drag : function(ev, ui) {
            // move the full sized content
            $fullContent.css('left', -1 * ui.position.left / scaleRatio );
        }
    });
});

Here, we've attached a draggable event and set a couple options. First, we set axis to restrict dragging to the x-axis, and then we set containment to confine dragging to the parent element (i.e. the controls wrapper).

Finally, we set up a drag listener to move the full-sized content according to how far the user has dragged the control. For this, we negatively positioned the content to the left by the drag amount multiplied by the ratio of the controls to the content.

Custom Cursors

The draggable content is working, but we still have room for improvement.

First let's add some more styling to the control box to make it more interactive. jQuery UI's draggable attaches two class names that we can use for this: ui-draggable and ui-draggable-dragging.

#drag-controls.ui-draggable {
    cursor: -moz-grab !important;
    cursor: -webkit-grab !important;
    cursor: e-resize;
}

#drag-controls.ui-draggable-dragging {
    cursor: -moz-grabbing !important;
    cursor: -webkit-grabbing !important;
    border-color: yellow;
}

In addition to applying a new border color to the active controls, this snippet also attaches a number of cursor properties, which use proprietary UI cursors available in Firefox and Safari, with a back-up for IE.

Because of the implementation of the cursor property, we had to "bootstrap" this together using !important. This ensures that the proprietary cursors are used if available, while allowing the default cursor to overwrite them in IE. Unfortunately, Chrome does not currently support -webkit-grab, so we leave it out of this implementation. If you'd prefer to use the back-up e-resize cursor in both Chrome and Safari, just remove the -webkit-grab and -webkit-grabbing properties.

Parallax Effect

Let's make the sliding animation more three-dimensional by adding a two-layer parallax effect. To do so, we simply add a background to our full-sized content area and animate it at a slower rate.

Add the mark-up first:

<div id="full-sized-area">
    <div id="full-sized-background">
    Your background here
    </div>

    <div id="full-sized-content">
    Your content here
    </div>
</div>

<div id="drag-controls-area">
    <div id="drag-controls"></div>
</div>

And then some basic styling:

#full-sized-background {
    position: absolute;
    top: 0;
    left: 0;
}

Here, we use absolute positioning to lock the background in place. Note that we did not need to attach a z-index, because we placed the background element before the content area in the mark-up.

Finally, let's add the background animation to our drag event:

    $fullBackground = $('#full-sized-background');

    $controls.draggable({
        axis : 'x', // confine dragging to the x-axis
        containment : 'parent',
        drag : function(ev, ui) {
            // move the full sized content
            var newContentPosition = -1 * ui.position.left / scaleRatio;
            $fullContent.css('left', newContentPosition);

            // move the background
            $fullBackground.css('left', newContentPosition * .4);
        }
    });

Here, we simply used the new position that we calculated for the main content and applied 40% of that change to the background. Adjust this value to change the speed of the parallax.

Download the complete example.

3. Subtle Hover Effects

Veerle in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Veerle's blog uses subtle transitions to create a natural feel for mouse interactions. These can be easily accomplished using CSS3's transition property (and a jQuery back-up for unsupported browsers).

First, let's attach some CSS with the class subtle to all elements:

.subtle {
    background-color: #78776C;
    color: #BBBBAD;
}

.subtle:hover, .subtle:focus {
    background-color: #F6F7ED;
    color: #51514A;
}

Here, we've styled these elements with a background and text color and included a hover state using the pseudo-class :hover. Additionally, we included the :focus pseudo-class for active input and text-area elements.

This CSS causes the style to change immediately on hover, but we can apply a smoother transition using CSS3:

.subtle {
    -webkit-transition: background-color 500ms ease-in; /* Saf3.2+, Chrome */
    -moz-transition: background-color 500ms ease-in; /* FF3.7+ */
    -o-transition: background-color 500ms ease-in; /* Opera 10.5+ */
    transition: background-color 500ms ease-in; /* futureproofing */
    background-color: #78776C;
    color: #BBBBAD;
}

.subtle:hover, .subtle:focus {
    background-color: #F6F7ED;
    color: #51514A;
}

Here, we've attached a CSS3 transition that works in all modern browsers except IE. The transition property consists of three different values. The first is the CSS property to animate, and the second is the duration of the animation—in our case, background-color and 500 milliseconds, respectively. The third value allows us to specify an easing function, such as ease-in or linear.

jQuery Back-Up

Our subtle transitions now work across a variety of browsers, but let's include support for all users by leveraging a jQuery back-up technique.

First we'll need to detect whether the user's browser supports transition:

// make sure to execute this on page load
$(function() {
    // determine if the browser supports transition
    var thisStyle = document.body.style,
    supportsTransition = thisStyle.WebkitTransition !== undefined ||
        thisStyle.MozTransition !== undefined ||
        thisStyle.OTransition !== undefined ||
        thisStyle.transition !== undefined;
});

Here, we check whether the body element can use any of the browser-specific transition properties that we defined above.

If the browser doesn't support transition, we can apply the animation using jQuery. However, jQuery's animate() function does not natively support color-based animations. To accommodate our background-color animation, we'll have to include a small chunk of jQuery UI: the effects core.

After including jQuery UI, we'll need to attach the animation to the hover and focus event listeners:

// make sure to execute this on page load
$(function() {
    // determine if the browser supports transition
    var thisStyle = document.body.style,
    supportsTransition = thisStyle.WebkitTransition !== undefined ||
        thisStyle.MozTransition !== undefined ||
        thisStyle.OTransition !== undefined ||
        thisStyle.transition !== undefined;

    // assign jQuery transition if the browser doesn't support
    if ( ! supportsTransition ) {
        var defaultCSS = {
            backgroundColor: '#78776C'
        },
        hoverCSS = {
            backgroundColor: '#F6F7ED'
        };

        // loop through each button
        $('.subtle').each(function() {
            var $subtle = $(this);

            // bind an event listener for mouseover and focus
            $subtle.bind('mouseenter focus', function() {
                $subtle.animate(hoverCSS, 500, 'swing' );
            });

            // bind the reverse for mouseout and blur
            $subtle.bind('mouseleave blur', function(ev) {
                if ( ev.type == 'mouseleave' && ev.target == document.activeElement ) return false;

                $subtle.animate(defaultCSS, 500, 'swing' );
            });
        });
    }
});

Here, we recreated the transition using jQuery's animate(). Notice how we used values that are to the CSS3 transition—500 specifies 500 milliseconds, and swing specifies an easing method that is close to ease-in.

While the mouse-over and focus event is fairly straightforward, notice the difference in the mouse-out and blur event. We added some code to end the function if the element is in focus. This retains the active state even if the user moves their mouse. jQuery's is() method does not support the :focus pseudo-class, so we have to rely on DOM's document.activeElement.

Download the complete example.

4. Comment Count Bars

Most-commented in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

IT Expert Voice uses a nice method for displaying the "Most commented" posts in its sidebar. Let's recreate this using WordPress and a bit of CSS and jQuery (non-WordPress users can skip the first section).

Pulling Posts With WordPress

Let's start by pulling in the top-five most-commented posts:

<?php $most_commented = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>

Here, we used WP_Query and a custom variable name so as not to disrupt any other post loops on the page.

Next, let's loop through the posts we've selected, outputting each as a list item:

<ul id="most-commented">

<?php $most_commented = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>
	<?php while ($most_commented->have_posts()) : $most_commented->the_post(); ?>	

	<li>
	<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>

	<span class="comment-bar"><span class="comment-count"><?php comments_number('0','1','%'); ?></span></span>
	</li>

<?php endwhile; ?>

</ul>

Here, we used a while() loop to run through each post. First, we output a link to the post using the_permalink() and the_title(), and then we output the comment count using comments_number() and some additional mark-up for styling.

Basic CSS Styling

Let's style the basic layout of the comments list using CSS:

#most-commented li {
    list-style: none;
}

#most-commented a {
    display: block;
}

We've removed any list styling and defined the links as a block element so that they stay separate from our comment bar visualizations.

Let's set up some base styles for the comment bar and comment count:

#most-commented .comment-bar {
    display: inline-block;
    position: relative;
    height: 30px;
    width: 0;
    margin: 5px 0;
    padding-left: 20px;
    background-color: #999;
}

#most-commented .comment-count {
    display: inline-block;
    position: absolute;
    right: -20px;
    top: -5px;
    width: 34px;
    height: 34px;
    border-width: 3px;
    border-style: solid;
    border-color: #FFF;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    border-radius: 20px;
    text-align: center;
    line-height: 34px;
    background-color: #6CAC1F;
    font-size: 13px;
    font-weight: bold;
    color: #FFF;
}

Most of this styling is arbitrary, so feel free to attach a background image or otherwise tweak it to fit your theme. The main thing is to align the comment count to the right of the comment bar so that we can adjust the width of the bar at will.

Pay attention to the total width of the comment count, in our case 40px (34px wide plus 3px for the left and right borders). We're using half of that value to position the comment count: 20px of negative positioning so that the count hangs on the right, and 20px of left padding so that the comment bar reaches the center of the comment count.

Tying It All Together With jQuery

Finally, let's use jQuery to set the widths of the individual bars. We'll start by looping through the comments after the page loads:

$(function() {
    $('#most-commented li').each(function(i) {
        var $this = $(this);
        var thisCount = ~~$this.find('.comment-count').text();
    });
});

We loop through all of the <li> elements, pulling out the comment count from the mark-up. Notice that we've used the primitive data type ~~ to convert the text to an integer. This is significantly faster than alternatives such as parseInt().

Let's set up some key variables in the first iteration of our loop:

$(function() {
    // define global variables
    var maxWidth, maxCount;

    $('#most-commented li').each(function(i) {
        var $this = $(this);
        var thisCount = ~~$this.find('.comment-count').text();

        // set up some variables if the first iteration
        if ( i == 0 ) {
            maxWidth = $this.width() - 40;
            maxCount = thisCount;
        }
    });
});

Here, we started by defining variables outside of the each() loop. This allows us to use these values in every iteration.

Next, we subtracted 40 pixels from the width of the list item to define a maximum width for the comment bar. The 40 pixels compensate for the left-padding and negative position that we applied above.

We also set maxCount to the first value. Because we initially pulled the posts according to their number of comments, we can be sure that the first item will have the highest count.

Finally, let's calculate the width of each bar and animate the transition:

$(function() {
    // define global variables
    var maxWidth, maxCount;

    $('#most-commented li').each(function(i) {
        var $this = $(this);
        var thisCount = ~~$this.find('.comment-count').text();

        // set up some variables if the first iteration
        if ( i == 0 ) {
            maxWidth = $this.width() - 40;
            maxCount = thisCount;
        }

        // calculate the width based on the count ratio
        var thisWidth = (thisCount / maxCount) * maxWidth;

        // apply the width to the bar
        $this.find('.comment-bar').animate({
            width : thisWidth
        }, 200, 'swing');
    });
});

If you'd rather style the elements without any animation, simply replace the animate() with a static css().

Download the complete example.

5. Full-Page Slider

Wine-jax in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Sliding animation is an interactive way to show related content. But JAX Vineyards takes the standard sliding gallery to the next level by animating across the entire page. Let's create a similar effect using jQuery.

Mark-Up and CSS

Start by adding the mark-up:

<div id="full-slider-wrapper">
    <div id="full-slider">

        <div class="slide-panel active">
        Panel 1 content here
        </div>

        <div class="slide-panel">
        Panel 2 content here
        </div>

        <div class="slide-panel">
        Panel 3 content here
        </div>
    </div>
</div>

We set up the basic mark-up and wrappers that we need for the animation. Make sure that the full-slider-wrapper is not contained in any element that is narrower than the browser window—we'll need the full width of the browser to pull off the effect.

Now, let's add some basic CSS to handle overflow and to position the panels:

html {
    min-width: 800px;
}

#full-slider-wrapper {
    overflow: hidden;
}

#full-slider {
    position: relative;
    width: 800px;
    height: 600px;
    margin: 0 auto;
}

#full-slider .slide-panel {
    position: absolute;
    top: 0;
    left: 0;
    width: 800px;
    height: 600px;
    visibility: hidden;
}

#full-slider .slide-panel.active {
    visibility: visible;
}

We defined absolute positioning and set up some arbitrary dimensions for the panels and wrapper. Feel free to tweak these dimensions to your content.

We also attached overflow: hidden to our wrapper element, which will prevent scroll bars from appearing when we animate the panels. Because we hid the overflow, we also had to assign a min-width to the html document. This ensures that the content will get scroll bars if the browser window is too small.

Finally, we used the active class that we established in the mark-up to show the first panel.

jQuery Animation

Let's build the interaction using jQuery. We'll start by defining some variables and then create a function to handle the sliding animation in both directions:

$(function() {
    var $slider = $('#full-slider');
    var $sliderPanels = $slider.children('.slide-panel');

    function slidePanel( newPanel, direction ) {
        // define the offset of the slider obj, vis a vis the document
        var offsetLeft = $slider.offset().left;

        // offset required to hide the content off to the left / right
        var hideLeft = -1 * ( offsetLeft + $slider.width() );
        var hideRight = $(window).width() - offsetLeft;

        // change the current / next positions based on the direction of the animation
        if ( direction == 'left' ) {
            currPos = hideLeft;
            nextPos = hideRight;
        }
        else {
            currPos = hideRight;
            nextPos = hideLeft;
        }

        // slide out the current panel, then remove the active class
        $slider.children('.slide-panel.active').animate({
            left: currPos
        }, 500, function() {
            $(this).removeClass('active');
        });

        // slide in the next panel after adding the active class
        $( $sliderPanels[newPanel] ).css('left', nextPos).addClass('active').animate({
            left: 0
        }, 500 );
    }
});

Here our slidePanel() function accepts two arguments: the index of the panel that we want to slide into view, and the direction of the slide (i.e. left or right).

Although this function looks complicated, the concepts are fairly simple. We determined the amount of offset necessary to hide the panels on the left and right sides. To calculate these values, we used jQuery's offset() and the slider and window widths. These offsets represent the left position values needed to hide the content on either side.

Next, we have a switch based on the direction of the animation, which uses the two values we defined previously.

Finally, we trigger the animation using jQuery's animate(). We slide the active panel out of view and then remove the active class once the animation completes. Then we set the new panel's left position off the screen, attach the active class to make it visible and slide it into place.

Building the Controls

Our function now handles the animation, but we still have to build controls to leverage it.

Append navigation elements to the slider object that we defined previously:

    var $navWrap = $('<div id="full-slider-nav"></div>').appendTo( $slider );
    var $navLeft = $('<div id="full-slider-nav-left"></div>').appendTo( $navWrap );
    var $navRight = $('<div id="full-slider-nav-right"></div>').appendTo( $navWrap );

We could have included this navigation in the initial mark-up, but we're appending it with JavaScript for two reasons: it ensures that the navigation won't appear until the JavaScript is loaded, and it keeps the navigation from being displayed on the off chance that JavaScript isn't enabled.

Let's style the navigation:

#full-slider-nav {
    position: absolute;
    top: 0;
    right: 0;
}

#full-slider-nav-left, #full-slider-nav-right {
    display: inline-block;
    height: 0;
    width: 0;
    margin-left: 15px;
    border: 20px solid transparent;
    cursor: pointer;
}

#full-slider-nav-left {
    border-right-color: #BBB;
}

#full-slider-nav-left:hover {
    border-right-color: #999;
}

#full-slider-nav-right {
    border-left-color: #BBB;
}

#full-slider-nav-right:hover {
    border-left-color: #999;
}

Here we absolute position the navigation to the top right. We also use a CSS triangle trick to quickly style the controls.

Let's attach our new slider navigation to the slidePanel() function that we defined previously:

    var $navWrap = $('<div id="full-slider-nav"></div>').appendTo( $slider );
    var $navLeft = $('<div id="full-slider-nav-left"></div>').appendTo( $navWrap );
    var $navRight = $('<div id="full-slider-nav-right"></div>').appendTo( $navWrap );

    var currPanel = 0;

    $navLeft.click(function() {
        currPanel--;

        // check if the new panel value is too small
        if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;

        slidePanel(currPanel, 'right');
    });

    $navRight.click(function() {
        currPanel++;

        // check if the new panel value is too big
        if ( currPanel >= $sliderPanels.length ) currPanel = 0;

        slidePanel(currPanel, 'left');
    });

This snippet assigns click events to the left and right navigation. In each, we change the value of currPanel according to the direction. If this new value falls outside of the available panels, we loop to the other end of our set. Finally, we trigger the slidePanel() function with the new panel and appropriate direction.

In our example, we built controls only for left and right navigation, but you could easily tweak this to have buttons for each panel. Simply pass the correct panel index to slidePanel.

Let's bring all the jQuery code together:

$(function() {
    function slidePanel( newPanel, direction ) {
        // define the offset of the slider obj, vis a vis the document
        var offsetLeft = $slider.offset().left;

        // offset required to hide the content off to the left / right
        var hideLeft = -1 * ( offsetLeft + $slider.width() );
        var hideRight = $(window).width() - offsetLeft;

        // change the current / next positions based on the direction of the animation
        if ( direction == 'left' ) {
            currPos = hideLeft;
            nextPos = hideRight;
        }
        else {
            currPos = hideRight;
            nextPos = hideLeft;
        }

        // slide out the current panel, then remove the active class
        $slider.children('.slide-panel.active').animate({
            left: currPos
        }, 500, function() {
            $(this).removeClass('active');
        });

        // slide in the next panel after adding the active class
        $( $sliderPanels[newPanel] ).css('left', nextPos).addClass('active').animate({
            left: 0
        }, 500 );
    }

    var $slider = $('#full-slider');
    var $sliderPanels = $slider.children('.slide-panel');

    var $navWrap = $('<div id="full-slider-nav"></div>').appendTo( $slider );
    var $navLeft = $('<div id="full-slider-nav-left"></div>').appendTo( $navWrap );
    var $navRight = $('<div id="full-slider-nav-right"></div>').appendTo( $navWrap );

    var currPanel = 0;

    $navLeft.click(function() {
        currPanel--;

        // check if the new panel value is too small
        if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;

        slidePanel(currPanel, 'right');
    });

    $navRight.click(function() {
        currPanel++;

        // check if the new panel value is too big
        if ( currPanel >= $sliderPanels.length ) currPanel = 0;

        slidePanel(currPanel, 'left');
    });
});

Download the complete example.

Final Thoughts

In this post we walked through a variety of methods for adding dynamic functionality to your websites. These techniques can be easily adapted to work with almost any site. The majority of these techniques rely on jQuery to provide interaction, but there are plenty of other approaches, both with and without jQuery. Please post any alternate solutions in the comments below, or fork the example files on github.

Furthermore, these five methods represent only a small portion of interactive techniques. Please post any links to other dynamic techniques and functionality in the comments below.

Related Posts

You may be interested in the following related posts:

(al)
Tweet


© Jon Raasch for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: javascript, jquery

September 03 2010

16:00

An open and shut case: At the new TimesOpen, different models for attracting developers to a platform

One phone rings, then another, then four more, now a dozen. The 15th-floor conference room is suddenly abuzz with an eclectic mix of song snippets and audio bits, an intimate peak at their owners before each is picked up or silenced. Having impressed the audience with the telephony technology behind the product, the presenter moves on to the next demo.

The intersection of mobile and geolocation is still an unknown world, waiting to be invented by hackers like the ones at round 2.0 of TimesOpen, The New York Times’ outreach to developers, which launched Thursday night. We wrote about the first TimesOpen event last year: It’s an attempt to open the doors of the The Times to developers, technologists, designers, and entrepreneurs, who can use Times tools to help answer some of the field’s big questions. This iteration of TimesOpen is a five-event series this fall, each focusing on a different topic: mobile/geolocation, open government, the real-time web, “big data,” and finally a hack day in early December.

On the docket Thursday were Matt Kelly of Facebook, John Britton of Twilio, Manu Marks of Google, and John Keefe of WNYC. Kelly presented Facebook Places; Britton gave one of his now New York-famous live demos of the Twilio API; Marks dove deep into the various flavors of the Google Maps API; Keefe — the only non-programmer of the bunch — discussed lessons learned from a community engagement project with The Takeaway.

Building community around an API

An API, or application programming interface, allow applications to easily communicate with one another. For example, any iPhone or Android application that pulls information from a web-based database is most likely it through an API. If you search local restaurants through Yelp, your location and query are passed to Yelp and results given in return. For any company with an API, like the three at TimesOpen, the challenge is to convince developers they should spend their time innovating on top of your platform. Strategically, when there’s an entire ecosystem living on top of your platform, your platform then becomes indispensable and valuable.

What’s most fascinating to me, however, are the approaches each company is taking to build a community around its API. The community is the most important key to the success of an API, a major source of innovation. One of the keys to Twitter’s explosive growth has been its API; rather than depending on its own developers for all new innovation, Twitter inadvertently created an entire ecosystem of value on top of their platform.

Let’s contrast Facebook and Twilio, for example. Facebook hopes Places, launched in mid August, will become the definitive platform for all location data. Interoperability can happen, but it should happen over Facebook’s infrastructure. Facebook envisions a future where, in addition to showing you where your friends are in real time, Places will also offer historical social context to location. Remember the trip through South America your friend was telling you about? Now you don’t have to, all of the relevant information is accessible through Places.

At the moment, though, Facebook’s only public location API is read-only. It can give a developer a single check-in, all check-ins for a given user, or check-in data for a given location. They have a closed beta for the write API with no definitive timeline for opening it publicly. Expanded access to the API is done through partnerships reserved for the select few.

Twilio’s demo power

Twilio, on the other hand, is a cloud-based telephony company which offers voice and SMS functionality as a service, and whose business depends wholly on extensive use of its API. Developer evangelist John Britton made a splash at the NY Tech Meetup when, in front of hundreds, he wrote a program and did a live demo that elegantly communicated the full scope of what their product offers. On Thursday, he impressed again: Using the Twilio API, he procured a phone number, and had everyone in the audience dial into it. When connected, callers were added to one of three conference rooms. Dialing into the party line also meant your phone number was logged, and the application could then follow up by calling you back. All of this was done with close to a dozen lines of code.

At TimesOpen, Britton stressed API providers need to keep a keen ear to their community. Community members often have ideas for how you can improve your service to solve the intermediate problems they have. For instance, up until a week ago, Twilio didn’t have the functionality to block phone numbers from repeatedly dialing in. For one company using the platform, the absence of this feature became a significant financial liability. Once rolled out, the feature made Twilio much more valuable of a service because the company could more closely tailor it to their needs. To make experimentation even easier, Twilio also has an open source product called OpenVBX and brings together its community with regular meetups.

Facebook already has the scale and the social graph to make any new API it produces a player. But for wooing the hackers — at least when you’re a small and growing platform — open and inclusive seems to win out over closed and exclusive.

August 30 2010

14:00

An iPhone app developer’s diary, and some thoughts on Android

The reaction to our new free iPhone app has been tremendously positive — if you’ve got an iPhone and haven’t downloaded it yet, I suggest you hop to. On my post announcing the app, there were a few comments I wanted to respond to. First, this one from Robin Sloan, who wants a little background on how the digital sausage got made:

I’d love to read a little mini “developer diary” about the behind-the-scenes process here — tools/frameworks you used, surprises along the way, etc. Bet it would be useful to a lot of folks working on iPhone apps at news organizations, too!

So, for those interested, here’s my tale of how the Lab iPhone app came into being — a tale I hope lots more news organizations can tell. Because if I can do it for a total cost of $624, there’s no reason more newspapers shouldn’t be on the platform.

Building with frameworks

I’m nerdier than your average journalist, and I’ve done some small, basic projects in Xcode — Apple’s development environment for Macs and iPhones/iPads — before. But there’s no way I could have built this app without the help of a framework. Frameworks are tools to abstract away layers of complication — they take a variety of common tasks and handle them for you, leaving you more time to deal with tasks specific to your app. (You may have heard of Django and Ruby on Rails, popular web frameworks for building web applications.)

The framework I used is TapLynx, which is aimed at building apps from one or more RSS feeds. It’s built by Brent Simmons, best known in the tech world as developer of the first great RSS reader for the Mac, NetNewsWire. Much of the guts of TapLynx uses the feed reading and parsing code from the iPhone version of NetNewsWire.

With RSS feeds as a base, the decisions around content are both more restricted and a little easier. We produce one major RSS feed — our posts. Another one comes from our Twitter feed. So those were obvious choices as the first two tabs. In TapLynx, creating tabs is largely a matter of editing a .plist file in Xcode with some simple customizations and editing an HTML template for the display of the individual story pages. If you don’t know any HTML or CSS, you’d find the latter a challenge, but the templating language is simple enough.

Beyond that, I knew I wanted to embed some of the best publicly available feeds related to journalism, so that the app could be a concentrated shot of news-about-news. And I also wanted it to be a tool that would also promote some of our friends here around Harvard. So I added a tab that would pull in some of those feeds called Friends of the Lab. That created some new challenges, since some of the feeds were malformed in a variety of ways. One didn’t present post dates correctly, so I ended up removing dates from the presentation of all feeds in the tab. (TapLynx, unfortunately, won’t let you customize presentation for different feeds in the same tab.) I also had to build in a few template-file CSS hacks for feeds that presented images incorrectly.

Shoehorning Hourly Press in

The most challenging tab (and the one that still needs some work) is the Hot Links tab. (The name is a slight nod to my Cajun heritage.) It uses Hourly Press, the great web service built by Steve Farrell and Lyn Headley, to pull in the most linked-to links in the future-of-news Twitterverse. For THP we define a set of “authorities” (see ours here) on Twitter; the people they follow end up having more weight in the system than people they don’t. Once an hour, everyone’s tweets are scanned for links, weighted according to how much authority the system gives them, and then output in a top-10 list. It’s perfect for those moments where you want a quick jolt of the biggest news of the moment, but curated within our particular field of interest.

Because TapLynx is optimized for RSS feeds, it’s a challenge to deal with HTML, which is THP’s output. I asked the THP guys to build an iPhone version of the rankings, formatted for the smaller screen and big fingers. But TapLynx works better with static HTML than with live web pages. So I ended up having to use a plugin called OOZWebView, built by Roberto Brega and expanded by Walter Tyree. It allows for some very basic web access in a tab. I even made a few changes to the code to allow user resizing of text in webpages — the only real Objective-C I wrote. It’s not perfect — refresh behavior is unreliable, particularly in iOS4 with state saving, and the UX looks as hacky as it is. But it was the best way available. (Any Objective-C coders want to help make it better? Lemme know.)

Lagniappe

Beyond that, the search tab just uses WordPress little-known search RSS feed to dive into our archives on command. There was a fair amount of Photoshop work to create transparent PNGs at precisely the right size (and again at twice that size, to look good on the better Retina Display of the iPhone 4). I built a few of the tab icons myself as greyscale PNGs with transparent alpha channels; others I took from the Glyphish collection of icons, including the Retina icons just released via Kickstarter. For the static About page and the Twitter template, I ended up using data URIs to embed our icon into the HTML itself — that prevented a weird resizing when the image was loaded after the rest of the page. And I, like many app developers, had to navigate the new waters of Twitter’s xAuth system (newly mandatory as of a few weeks ago) to allow tweeting from within the app.

All this is to say that the process was more complicated and self-directed than most people would be able to manage — but easy enough that any shop that has a Mac and a few nerds could pull it off. There’s nothing impossibly hard here. From my viewpoint, I don’t understand why more news organizations don’t use frameworks to build out apps quickly and easily. Even if the ad revenue from a mobile app isn’t astounding, it’s still better than nothing — and it’s a foot in the door for increasingly mobile news consumers.

The upfront costs of development were minimal. I paid $500 for a license to TapLynx (it currently goes for $599). It was $99 to get into Apple’s iPhone developer program and $25 for the Retina Glyphish icons. Total cost: $624. And a fair amount of my time, to be honest.

One constant throughout the process was that there were factors outside my control. Our app would have launched sooner if Apple hadn’t made the move to iOS 4, which necessitated waiting for a new TapLynx library to work with it. It would have launched sooner if the impending Twitter xAuth switchover hadn’t made me wait. It would have launched sooner if I wasn’t relying on the generous work of guys like Roberto and Walter to made one of my tabs function. And, frankly, it would have launched sooner if I wasn’t doing all this work on evenings and weekends around my other duties — or if I’d been happy with something closer to the TapLynx defaults in a number of cases.

Now comes the challenge of keeping the thing up-to-date and functional. They say a band has a lifetime to write its first album and six months to write its second; I feel the same thing is true for version 1.0 and version 1.01. I’ve already got a list of improvements and fixes ready to move on. I’d love to hear any suggestions on how to make it better.

On Android, BlackBerry, WebOS, Windows Phone, Symbian, et al.

Back to my original post. Another thread of comments — on the post and on Twitter — were from people upset there’s only an iPhone app. “Nothing for Android, huh?” one commenter wrote. “Seems shortsighted.” Others on Twitter called out for a BlackBerry app, or an iPad-specific app. (I didn’t see any calls for Windows Mobile/Phone, Symbian, or WebOS.) There are a few reasons why we’re just on the iPhone right now.

We’re tiny. The Nieman Journalism Lab is currently three people in a basement. (Two iPhones and one BlackBerry, if you’re counting.) Along with being director, I’m also house nerd. Our budget doesn’t allow for big investments in technology, which is why I ended up building the iPhone app as a personal side project. I’ve been a Mac guy since the early 1990s and an iPhone guy since 2007, so my own personal interests and knowledge base are going to play a role in what I develop in my spare time.

Our mobile audience is overwhelmingly on Apple devices. Here’s data from the past 30 days, as of August 24, 2010: 84 percent Apple (45 percent iPhone, 35 percent iPad, 4 percent iPod touch); 10 percent Android; 5 percent BlackBerry; 0.3 percent Symbian; 0.2 percent Windows Mobile.

(If you’re curious about the overall numbers for desktop and mobile combined, our readers are about 54 percent Windows, 34 percent Mac, 4 percent iPhone, 3 percent iPad, 3 percent Linux, 1 percent Android, 0.5 percent BlackBerry.)

If, as some predict, Android sweeps aside the iPhone and becomes the dominant platform on mobile, then maybe we’ll build one. But for now, we’re just putting our limited resources where we think they can have the most impact.

We need the tools. As I said above, if there wasn’t a framework like TapLynx to make the process easier, we wouldn’t even have an iPhone app. Google’s new App Inventor would seem to be a move in that direction, but the initial reviews I’ve read don’t make it seem particularly user-friendly. (And this TechCrunch piece indicates “there isn’t any RSS functionality baked in” App Inventor, which would limit its usefulness for our app.)

That said, I don’t pretend to be up to date on the latest state of Android development frameworks — or their equivalents on other platforms. If someone out there is interested in volunteering to help build an Android (or WebOS, or BlackBerry, or Windows Phone, or Symbian) version, I’d love to hear from you. We’ve got no animus against other platforms; we just don’t yet see an audience big enough to justify our scant resources.

August 10 2010

08:00

#Tip of the day from Journalism.co.uk – html5 tagging

Get up to date with html5 tagging using Currybet.net's blog post outlining some of the 30 new tags for coding page structure, article structure and semantic mark-ups. Tipster: Rachel McAthy. To submit a tip to Journalism.co.uk, use this link - we will pay a fiver for the best ones published.


June 02 2010

20:42

Why Journalists Should Learn Computer Programming

Yes, journalists should learn how to program. No, not every journalist should learn it right now -- just those who want to stay in the industry for another ten years. More seriously, programming skills and knowledge enable us traditional journalists to tell better and more engaging stories.

Programming means going beyond learning some HTML. I mean real computer programming.

As a journalist, I'm full aware of the reasons why we don't learn programming -- and I'm guilty of using many of them. I initially thought there were good reasons not to take it up:

  • Learning to program is time-consuming. One look at the thick books full of arcane code and you remember why you became a journalist and not a mathematician or an engineer. Even if you are mathematically inclined, it's tough to find the time to learn all that stuff.
  • Your colleagues tell you you don't need it -- including the professional developers on staff. After all, it took them years of study and practice to become really good developers and web designers, just like it takes years for a journalist to become experienced and knowledgeable. (And, if you start trying to code, the pros on staff are the ones who'll have to clean up any mess you make.)
  • Learning the basics takes time, as does keeping your skills up to date. The tools change all the time. Should you still bother to learn ActionScript (Flash), or just go for HTML5? Are you sure you want to study PHP and not Python?
  • Why learn programming when there are so many free, ready-made tools online: Quizzes, polls, blogs, mind maps, forums, chat tools, etc. You can even use things like Yahoo Pipes to build data mashups without needing any code.
  • When Megan Taylor wrote for MediaShift about the programmer-journalist, she asked around for the perfect skillset. One response nearly convinced me to never think about programming ever again: "Brian Boyer, a graduate of Medill's journalism for programmers master's track and now News Applications Editor at the Chicago Tribune, responded with this list: XHTML / CSS / JavaScript / jQuery / Python / Django / xml / regex / Postgres / PostGIS / QGIS."

Those are some of the reasons why I thought I could avoid learning programming. But I was so wrong.

Why Journalists Should Program

You've heard the reasons not to start coding. Now here's a list of reasons why you should:

  • Every year, the digital universe around us becomes deeper and more complex. Companies, governments, organizations and individuals are constantly putting more data online: Text, videos, audio files, animations, statistics, news reports, chatter on social networks...Can professional communicators such as journalists really do their job without learning how the digital world works?
  • Data are going mobile and are increasingly geo-located. As a result, they tell the stories of particular neighborhoods and streets and can be used to tell stories that matter in the lives of your community members.
  • People have less time, and that makes it harder to grab their attention. It's essential to look for new narrative structures. Programming enables you to get interactive and tell non-linear stories.

Jquerylogo copy.jpg

  • You don't have to build everything from scratch. Let's take JavaScript, which is used for creating dynamic websites. Tools such as jQuery, a cross-browser JavaScript library, enable people to create interactivity with less effort. Web application frameworks such as Ruby on Rails and Django support the development of dynamic sites and applications. So it can be easier than you thought.

A Way of Looking At the World

Maybe you're not yet convinced. Even though jQuery makes your life easier, you still need a decent knowledge of JavaScript, CSS and HTML. Django won't help you if you never practiced Python. All of this takes time, and maybe you'll never find enough of it to get good at all this stuff.

Still, we must try. The good news is that it doesn't matter if you become proficient at the latest language. What is important, however, is that you're able to comprehend the underpinnings of programming and interactivity -- to be able to look at the world with a coder's point of view.

I'm still just a beginner, but I feel that this perspective provides you with an acute awareness of data. You start looking for data structures, for ways to manipulate data (in a good sense) to make them work for your community.

When covering a story, you'll think in terms of data and interactivity from the very start and see how they can become part of the narrative. You'll see data everywhere -- from the kind that floats in the air thanks to augmented reality, to the more mundane version contained in endless streams of status updates. Rather than being intimidated by the enormous amount of data, you'll see opportunities -- new ways to bring news and information to the community.

You probably won't have time to actually do a lot of the programming and data structuring yourself. But now you're equipped to have a valuable and impactful conversation with your geek colleagues. A conversation that gets better results than ever before.

So, even though it's probably a bit late for me to attend the new joint Master of Science degree program in Computer Science and Journalism at Columbia University, I can still learn How to Think Like a Computer Scientist using the the free MIT OpenCourseWare, take part in the Journalists/Coders Ning network, and find help at Help.HacksHackers.Com).

And so can you.

******

Are you a journalist who has taken up programming? A programmer with advice for journalists? Please share your experiences and insights in the comments.

Roland Legrand is in charge of Internet and new media at Mediafin, the publisher of leading Belgian business newspapers De Tijd and L'Echo. He studied applied economics and philosophy. After a brief teaching experience, he became a financial journalist working for the Belgian wire service Belga and subsequently for Mediafin. He works in Brussels, and lives in Antwerp with his wife Liesbeth.

This is a summary. Visit our site for the full post ».

May 17 2010

10:13

Developers and journalists forging common ground

Back in April 2009 I listened as a group of bloggers at the G20 protests in London sent in reports using the new Audioboo iPhone application. The rules of the game are clearly changing fast, I thought.

The application allows users to record and upload high-quality sound files in an instant. In the same way that a photo of a plane floating in the Hudson river circumvented traditional channels and made its way around the world online, journalists (including Guardian staff) and bloggers on the ground were able to instantly upload reports on the unfolding activity with the immediacy and colour of front-line reports. I happened to be home ill that day and listened to the action with fascination. Then a contact from ABC News in the States contacted me via Twitter asking me if I knew any of the reporting bloggers and to pass on the direct number of the ABC newsroom. It was quick, energised and direct, and I was immediately hooked.

On the surface, the domain of the journalist and the developer seem poles apart. Journalists trace and shape stories, uncover information, and on a good day bring hidden truths to light. Developers build tools, marshal data and on a good day make the impossible possible. But a convergence is taking place that will ultimately rewrite the rulebook for both camps. Journalists have long been sifting and filtering forbidding mountains of data, looking for a story in the noise. Now they are going further, familiarising themselves with the tools to cohere and present this data, adapting to remain relevant in the new digital space. Developers in turn are doing far more than pushing data around. With rich social media tools and networks available to all, they are starting to report, telling stories with code and changing the way people in the online world relate, work and communicate. It’s a vast social experiment taking place in the production environment of the real world.

Back in March of this year, a small group of developers and journalists met in a pub in Islington to explore this overlap between coding and journalism in an intensely pragmatic fashion – the former teaching the latter the rudiments of web programming over a few beers. Ruby In The Pub was born.

A few days before, I overheard an online conversation between Joanna Geary of the Times and self-proclaimed ‘relapsed blogger’ James Ball. They were discussing the possibility of starting a regular event to get developers and journalists together. They touted Ruby as a possible language and with a speed typical of events incubated in social media circles the venue was sourced and the date decided.

As a Ruby developer (with the penchant for the odd beer) I immediately decided to attend and offer whatever support I could. The first event was warm and freestyle in nature, and the second drew a significantly larger group to the Shooting Star in Spitalfields, including the lead developer of the New York Times. One whole side of the pub was taken over by laptops and energised conversation. Due to the spotty wifi, I hardly managed any teaching at all, but became engaged in a wider discussion around journalism, the digital arena, and the changing media landscape.

Like that difficult third album, the next meet-up will probably define the future of this freestyle session. Ideas will gain traction, people will gravitate to familiar faces or pick up on projects that have been discussed. Karen Barber of Audioboo will be in attendance and has already taken up my offer of help on a project she has been kicking around for a while. We’ll get a drink, sit down, and start building it, responding to feedback from newbies and experienced hackers as we do so. Along the way, the communication channels between both sides will be strengthened and clarified and, what with all the activity on Twitter around the event, feelers of energy will spread out and spark up satellite meetings.

In fact, this has already happened. Paul Bradshaw, a journalist who teaches the MA in Online Journalism at Birmingham University, has already activated the wonderfully-named Ruby Tuesday up North and hopefully we’ll see a lot more. In a series of regular posts I will attempt to cover the process as it unfolds, as well as looking at the wider interface between word and code.

There’s no end to this journey, it’s a vibrant buzz of collaboration and exploration. Why not join us?

Similar Posts:



May 03 2010

22:26

Where/How do you store code snippets?

Anyone have any favorite ways of storing bits of code that you might want to incorporate at a later time?

I'm wondering what those in this group do (what your process is) when you're working on something that isn't quite ready for the formality of version control.

Scratch pad in text editor? Private repository? Whiteboard in the cloud? Commented-out code until cleanup?

Example scenario:
You're working on a project and decide you might eventually need some code that will provide cool Feature A. You create a chunk of Feature A. It's not quite ready for prime time and unnecessary for the project launch, but it could lead to something good. Where/how would you store the Feature A code?

A little further along, you come up with Feature B, which could be used in several other projects. Maybe. You put time and effort into Feature B, though, so you want to save the code, but again, not in a project. Where/how would you store it?

TIA.

April 20 2010

15:09

How do I cross the divide between code and journalism?

I am a web developer, primarily in Ruby (and Rails, Sinatra etc), but am trying to push my career into journalism as I know there will be roles for coder-journalists and would love to occupy that space. My question is, where do I start? I believe I possess strong writing skills but have no formal training in journalism.

Importantly, I am from the UK and as far as I am aware there aren't any educational establishments offering the kind of program Columbia, for example, runs here in Britain.

April 13 2010

09:40

February 02 2010

09:15

December 16 2009

13:53

Stronger, Better, Faster Design with CSS3

Smashing-magazine-advertisement in Stronger, Better, Faster Design with CSS3
 in Stronger, Better, Faster Design with CSS3  in Stronger, Better, Faster Design with CSS3  in Stronger, Better, Faster Design with CSS3

Spacer in Stronger, Better, Faster Design with CSS3

Stronger, Better, Faster Design with CSS3 (via @smashingmag) -

In our last article about CSS3, “Pushing Your Buttons With Practical CSS3, we talked about using new CSS3 techniques like gradients, border-radius and drop-shadows to create compelling, flexible and (in some cases) hilarious buttons.

In this second article we’re going to focus on using those CSS techniques (and a little JavaScript) to create some practical elements and layouts. As before, caveat coder — a lot of the CSS properties we’re going to use have limited support, if any, in IE6/7 and probably 8. Firefox 3.5+ and Safari 4 are your best bet right now to see all the cool stuff going on in CSS right now (Chrome does a pretty good job, too).

Why bother with CSS that has such limited support? It won’t always have limited support, and these articles are all about preparing for the future of web design (and just doing some really cool stuff). Apparently, if you are one of those people who is waiting until using progressive CSS is safe because all major browsers support the same CSS at the same time, you are living in a fantasy world, so it’s just the right time to get things rolling with CSS3.

Ready? Let’s roll.

Inline Form Labels

Everyone’s familiar with inline form labels — storing the label of the field in the value attribute and using some minor JavaScript to erase the text when the field gains focus. This works…okay, but the major problem is that as soon as the user clicks, they lose the label entirely. If they tabbed right into it they may not even have read the label, in which case they’re just guessing.

The first site we saw that fixed this was MobileMe from Apple, on their login screen.

Inline-1 in Stronger, Better, Faster Design with CSS3

What happens with Apple is that clicking into the field fades the label back, but doesn’t erase it. Cooler still is that the cursor stays positioned left so you can start typing, and the JavaScript making that happen is not overly complex — it’s just layout tricks. They position a label behind the input containing the name of the field.Inline-2 in Stronger, Better, Faster Design with CSS3 When you click into the field they use JavaScript to apply a class to the label that knocks it back, and another class as you start typing to make the label vanish.

We wrote a blog post about this effect some time ago, describing how you could replicate it yourself. The problem is that over time setting up the page to support this isn’t as turnkey as we’d like, so we’ve revised and rebuilt it just for you (and, of course, for us).

The New Inline Label

Our new approach is considerably easier — to use it in our own products (like Notable and Scrumptious) we simply add class="inlined" to the label and voila! Here’s how we do it.

Start with a regular label and input:

	<label for="demoForm1">Email Address</label>
	<input class="input-text" id="demoForm1" />

In previous iterations of this technique we went to the trouble of wrapping the label and input in a block-level element and used absolute positioning to put the label behind the input. Not anymore. First, we’ll add the “inlined” class to only the label:

	<label for="demoForm1" class="inlined">Email Address</label>
	<input class="input-text" id="demoForm1" />

Now we need to do a couple of things to get our labels to display correctly. First, we use negative margins to pull the input up and over the label. We’ll do this by using the CSS adjacent selector, which looks like this:

	label.inlined + input.input-text {
		margin-top: -22px;
		background-color: transparent;
		position: relative; z-index: 2;
	}

That code tells the browser to apply the style to any input.input-text which immediately follows a label.inlined — this way we can use the negative margin to pull the input up and over the label itself. We also set the background color to transparent and give the input a relative position and a z-index value.

Next we need to style the label itself. You’ll need to adapt the styling here to mirror your input text style — the goal is for the text inside the label to appear as though it is actually part of the input. Here are the critical pieces:

	label.inlined {
		padding-left: 6px;
		font: normal 12px/18px "Helvetica Neue";
		position: relative; z-index: 1;
		opacity: 0.75;
		-webkit-transition: opacity 0.15s linear;
	}

Let’s break that down. Padding and font are simply to mirror the input style. The positioning and z-index make sure the label stays behind the input — otherwise the input can’t be selected. Now the fun parts: opacity and -webkit-transition.

Our form labels work by fading back the label at different points. We start with the label faded back a little, hence the opacity: 0.75. You could also use color to drop the label back, but opacity works regardless of the font color. We add in the -webkit-transition so that whenever the opacity changes, the browser (Safari or Chrome, in this case) will change the opacity smoothly over about 1/8th of a second. So when does the opacity change?

Two times — when the user focuses on the field, and when they start typing. Let’s create two CSS classes we can apply for those states: focus and has-text.

	label.focus {
		opacity: 0.35;
	}

	label.has-text {
		opacity: 0.0;
		-webkit-transition-duration: 0s;
	}

As you can see, we reduce the opacity of the label when the user clicks in, then make it invisible when they start to type. We change the duration of our transition so that as a user starts to type, the label disappears immediately, rather than fading back as they type. Now that we have our fields structurally set up and styled the way we want, the last step is a little bit of JavaScript.

Adding the JavaScript

Even though CSS3 has added new tricks like animations and transitions, JavaScript is still king when it comes to interaction. To get our labels to behave, we need to use a few simple JavaScript functions. In these examples we’ll be writing for jQuery, but they’re easy to adapt to Prototype or straight JavaScript.

The JavaScript needs to do three things:

  1. Add the focus class to the label when the user clicks into a field
  2. Add the has-text class as soon as they start typing
  3. Bring the label back if they leave the field empty and switch to another field.
$(document).ready(function(){
	$("label.inlined + input.input-text").each(function (type) {

		$(this).focus(function () {
			$(this).prev("label.inlined").addClass("focus");
		});

		$(this).keypress(function () {
			$(this).prev("label.inlined").addClass("has-text").removeClass("focus");
		});

		$(this).blur(function () {
			if($(this).val() == "") {
				$(this).prev("label.inlined").removeClass("has-text").removeClass("focus");
			}
		});
	});
});

We won’t pore over the JavaScript much — it’s pretty self-explanatory. jQuery let’s us quickly target the inputs we want by recognizing the same selector we’re using in CSS, but otherwise it’s all cut and dried. And there it is: inline labels that appear as refined versions of standard inline labels, but have much smoother interaction. Going forward now we can make any label inline by adding class="inlined" to the label — CSS and JavaScript will take care of the rest.

Inline-form-labels in Stronger, Better, Faster Design with CSS3
See the Live Demo »

We’ve created a live demo page for these forms in our Playground, a place for us to create small side projects and examples of cool toys. We’ll be linking to the Playground examples throughout this post and the rest of the series.

Fast, Easy Drop-in Modals

Next we’ll show you how to create easy modals that you can control with just one line of JavaScript. We use modals to great effect in our feedback tool, Notable, and while in Notable we use Ajax to load modals on the fly, this example will show you how easy it is to create an on-page modal.

The basic structure of our modals is a div.modal containing whatever we want. It could be an alert triggered by your page, a sign-in or sign-up form, or other information or actions that we don’t want to trigger a full page load. We’ll use some of our new CSS3 styles to make the modals look awesome and feel…well, modal, then turn them on with a single line of JavaScript.

The Simple Modal

Our first modal example is a simpler style, with a simpler animation. We’ll style the div to resemble a padded, floating box with a standard drop shadow so it appears to hover over the page. To make it appear, we’ll fade it up from an opacity of 0, and to close it, we’ll dismiss it immediately.

Modal-1 in Stronger, Better, Faster Design with CSS3

The modal style here uses a couple new CSS3 elements: -webkit-box-shadow to create the drop shadow and -webkit-transition (which you’ll recognize from the inline labels above) to fade it in without using JavaScript animation. Below are the styles for the modal; we’ll go over the new pieces in a second.

	div#simpleModal {
		width: 560px;
		position: absolute; top: 40px; left: 170px;
		padding: 20px;
		border: solid 1px #bbb;
		background: #fff;
		-webkit-box-shadow: 0px 3px 6px rgba(0,0,0,0.25);
		-webkit-transition: -opacity 0.0s ease-out;
	}

	div#simpleModal.shown {
		opacity: 1.0;
		z-index: 100;
		-webkit-transition-duration: 0.25s;
	}

Most of the styling here is pretty standard — size and position as well as decent padding and a light grey border. The new pieces here are -webkit-box-shadow and -webkit-transition. We covered both of those new attributes in our article on CSS3 buttons so we’ll go over them quickly.

-webkit-box-shadow (or box-shadow as it will be called when the CSS3 spec is finalized and implemented) takes a few arguments. The first two properties are the offset, X and Y. In this case no X offset, 3px of Y offset. This puts the shadow just below the object. The next argument, 6px, sets the spread size: 6 pixels out from the box shape.

Finally we set a box-shadow color using RGBa, which lets us set an RGB color (black, in this case) and then set an opacity, or alpha channel. By using black with 25% opacity we can be sure it will darken whatever color it overlays; if we used something like #333 it would actually appear to glow on a black background, rather than look like a shadow.

The Fancy Modal

That modal is okay — it gets the job done and once you know it, the pieces can be put together in less than 5 minutes. We wanted to do a little more for Notable, so we cooked up a fancier style using a few other CSS tricks like -webkit-gradient and -webkit-transform.

Modal-2 in Stronger, Better, Faster Design with CSS3

This modal is a little flashier and more akin to a desktop app in terms of interaction: it slides down from the top and gets a little more chroming than the simple modal. We accomplish this through a couple of cool tricks.

	div#fancyModal {
		display: block; width: 560px;
		position: absolute; top: -310px; left: 170px;
		padding: 90px 20px 20px 20px;
		border: solid 1px #999;
		background: -webkit-gradient(linear, left top, left bottom, from(rgb(255,255,255)), to(rgb(230,230,230)));
		-webkit-box-shadow: 0px 3px 6px rgba(0,0,0,0.25);
		-webkit-border-bottom-left-radius: 6px;
		-webkit-border-bottom-right-radius: 6px;
		-webkit-transition: -webkit-transform 0.25s ease-out;
		-webkit-transform: translateY(-570px);
		-moz-box-shadow: 0px 3px 6px rgba(0,0,0,0.25);
		-moz-border-radius: 0 0 6px 6px;
		-moz-transform: translateY(-570px);
	}

First we generate a gradient for the background. Obviously we could just create a tiling background image for the gradient, but where’s the fun in that? We’ll have the browser create one using -webkit-gradient, which is a CSS function that creates a gradient you can use anywhere you would use an image. As you can see above, -webkit-gradient has quite a few attributes; it’s not as bad as it seems. Let’s break it down:

  • linear means that this gradient goes from one point to another, in a straight line. You can also use radial to create a circular gradient.
  • left top, left bottom are the coordinates for starting and stopping, in this case going from top to bottom with no angle. If we used left top, right bottom the gradient would stretch diagonally across the div.
  • from(rgb(255,255,255)) is the starting color, in this case white.
  • to(rgb(230,230,230)) is the ending color. We could also put color-stop elements in between if we wanted to vary the color as we went.

That wasn’t so hard! Gradients are going to be a great way to add those flourishes to design without having to futz around with image backgrounds – these are easily created and modified in just a couple of lines. Now let’s look at the fancier part of this modal: the appearance animation.

	div#fancyModal {
		…
		-webkit-transition: -webkit-transform 0.25s ease-out;
		-webkit-transform: translateY(-570px);
	}

What we’re doing here is using a property called -webkit-transform to move the modal up and out of the viewport. Since transforms don’t impact the DOM we don’t get any weird effects or problems — the div just moves up without impacting anything else. So when the page loads, our div will be located above the page. When we add class="shown" to the div, it will get a new transform position, and the -webkit-transition will cause the transformation to be applied over a quarter of a second — this is what causes the modal to slide down from the top of the page.

As you can see, creating a fairly fancy modal style is pretty easy with these new CSS3 effects. Our last step is a simple line of JavaScript to apply a shown class to the modal. For our simple modal, it changes the opacity to 1; for our fancy modal, it changes the transform position to 0 (rather than -570px). Our transition then takes care of the actual animation.

Drop-in-modals in Stronger, Better, Faster Design with CSS3
See the Live Demo »

You can check out the live demo on the Playground. We’ve got the source code and clickable examples of the two modals (requires WebKit).

Newspaper Layouts with Columns and Image Masks

Our final example in this article will demonstrate how to use a couple of new CSS attributes and functions to create a cool newspaper layout — in this case the Super Awesome Times.

The faux-newspaper look goes in and out of style online pretty frequently, but these tricks can be used for quite a few cool applications. What we’ll talk about here is using -webkit-mask-image and -webkit-column-count.

Using Image Masks

Image masking is a way to affect the alpha channel of a block-level element by masking it with another image (or anything that can take the place of an image, like a gradient). For the Super Awesome Times we wanted to apply a subtle gradient to the masthead. We could simply render an image, but that’s no fun. Instead we masked the text (which in this case is an image, but with @font-face you could use text instead) with a generated gradient. Check it out:

	div#masthead img {
	-webkit-mask-image:
		-webkit-gradient(
			linear,
			left top, left bottom,
			from(rgba(0,0,0,.75)), to(rgba(0,0,0,1)));
	}

The only property we need is -webkit-mask-image — the browser will use whatever you supply to create an alpha mask for the image or block element you’ve applied the mask to. In this case we use a gradient, which causes the masthead to fade from 75% opacity to 100%. Below is the masthead with the mask, and without — so you can see the difference:

Newspaper-1 in Stronger, Better, Faster Design with CSS3

It’s a subtle change, but some added depth can go a long way. There’s a great introduction to using masks over on Surfin’ Safari, the official WebKit blog. You can see how masks can be used for all sorts of interesting effects — even masking out an actual playing video.

Stunningly Easy Text Columns

Finally, we’ll show you how to use a new (and very poorly supported, so far) property in CSS3: text columns. Not the floated div kind, but the kind where you can simply set the number of columns and the gutter and have the browser do the rest.

Newspaper-2 in Stronger, Better, Faster Design with CSS3
3 columns, no fuss.

In the example above you can see three columns of text, but if you click through to the live example and view the source code, you’ll see that we’ve used just one div containing a number of paragraphs. Nothing tricky, no floats, no bizarre height manipulations — we’re just telling the browser to put the content of that block into 3 columns with 15px of space between them. Here’s how:

	div.three-col {
		-webkit-column-count: 3;
		-webkit-column-gap: 15px;
		-moz-column-count: 3;
		-moz-column-gap: 15px;
	}

That’s it! Simple, easy markup and styling. The catch here is that even in forward-thinking browsers this property has pretty poor support — there are a number of other properties (like dividers, breakers, etc) that haven’t been implemented or at all supported yet. This is just a taste of what’s to come — simple columns are on the way, but not here just yet.

Newspaper-layout-th in Stronger, Better, Faster Design with CSS3
See the Live Demo »

Check out the Super Awesome Times on the Playground – just creating this prototype got some cool ideas kicking for our own site and blog.

Coming Up in CSS3…

We hope you enjoyed this further foray into CSS3. You can still check out our article on CSS3 buttons (including one which, no kidding, glows radioactively). Stay tuned for the third and final article in the series, where we’ll take the CSS properties and really go to town with polaroids, an OS X dock, vinyl album music players and more.

References and Resources:


© ZURB for Smashing Magazine, 2009. | Permalink | 61 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: CSS, css3

Tags: Coding CSS css3

July 18 2008

09:22
Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl