All posts by patorjk

CSS3 Card Flip Animation Trick

I’ve been playing around with some of CSS3’s new animation features. For an app I’m writing, my wife suggested I jazz things up a bit by having an image look like its flipping over, and I realized that with CSS3, I could actually do that. To demonstrate what I’m talking about, in the latest version of Chrome, click one of the playing card images below*.

The neat thing is that the effect is ridiculously simple. The one catch is that you can’t change the background-image property of a div during an animation. To get around this, you just need to use an image that contains all of the pictures you want to display. When the image is out of view (e.g., roated at 90 degrees or 270 degrees on the Y axis), you change the background-position. That way, when the image rotates back into view, it’s displaying a different picture.

It’s pretty simple, but kind of amusing. Below is some example code you can use for your own animations. The card image used in this example can be seen here, and the full set of cards can be obtained here.

CSS:

@-webkit-keyframes card1Flip {
    0% {-webkit-transform: rotateY(0deg);}
    24% {background-position-y:0px;}
    25% {background-position-y:204px;}
    50% { -webkit-transform: rotateY(180deg);}
    75% {background-position-y:204px;}
    76% {background-position-y:0px;}  
    100% {-webkit-transform: rotateY(360deg);}
}
.card1FlipProps {
    -webkit-animation-name: card1Flip;
    -webkit-animation-duration: 2000ms;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: 1;	
    -webkit-animation-direction: normal;
    -webkit-animation-delay: 0;
}
#card1 {
    background-image:url('/images/blog-2011/card_map.png');
    width:150px;
    height:204px;
}

JavaScript:

var elm;
elm = document.getElementById("card1");
elm.addEventListener("webkitAnimationEnd", function(){
    if (this.classList) {
        this.classList.remove('card1FlipProps');
    }
}, false);
elm.addEventListener("click", function() {
    if (this.classList) {
        this.classList.add('card1FlipProps');
    }
}, false);

HTML:

<div id="card1"></div>

* Important Notes: Unfortunately, the CSS3 animation module isn’t implemented in most browsers right now, so the above example will only work in the latest version of Chrome. Safari also uses Webkit as its layout engine, however, when I tested this example in the latest version of Safari (5.0.5), it didn’t work correctly. Some digging around showed that my version of Safari was using Webkit version 533.21.1, and my version of Chrome was using Webkit version 534.30.

Since the animation module is still being worked on right now, this technique, and animations in general, should probably be used cautiously and for effects that aren’t that important.

Extendible BBCode Parser in JavaScript

Photo By Dean Terry

I decided to try my hand at implementing a BBCode parser in JavaScript. You can play around with it online here, and download the source here.

I had looked around a little bit and noticed that the existing JavaScript BBCode parsers had at least a few of the following issues:

  • They didn’t report errors on misaligned tags (e.g., [b][u]test[/b][/u]).
  • They couldn’t handle tags of the same type that were nested within each other (e.g., [color=red]red[color=blue]blue[/color]red again[/color]). This happens because their regex will look for the first closing tag it can find.
  • They couldn’t handle BBCode’s list format (e.g., [list][*]item 1[*]item 2[/list]).
  • They didn’t report errors on incorrect parent-child relationships (e.g., [list][td]item 1?[/td][/list]).
  • They weren’t easily extendible.

I naively thought it’d be easy to quickly whip up a parser, and at first it was. Most BBCode tags can be implemented with a simple find and replace. However, I quickly ran into the issues of dealing with nested tags of the same type, the noparse tag, and the list tag’s annoying [*] tag (which doesn’t have a closing tag). Luckily, I came across a neat blog post on finding nested patterns in JavaScript, which came in handy for isolating tag pairs, from the inner-most on up. Taking the idea from that post, one can do something like this to process the inner tags first and avoid the nested tag problem:

var str = "[list][list]test[/list][/list]",
    re = /\[([^\]]*?)\](.*?)\[\/\1\]/gi;
while (str !== (str = str.replace(re, function(strMatch, subM1, subM2) {
    return "" + subM2 + "";
})));
// str = "test"

That idea works well, though you can’t implement a noparse tag if you process the inner-most tags first. So I decided to pre-process the BBCode with something similar to the idea above and add in nested-depth information to each open and close tag. Once all of the tags had that, I could parse the processed code with a regex that could easily match-up the correct open and close tags.

To get around the issue of the [*] tag having no closing tag, I wrote code that inserted [/*] tags where they were supposed to go during the pre-processing period. I wont go into the algorithm here, but you can dig into the code if you’re interested.

Also, I should note that the fact that JavaScript allows you to use a function as the second parameter to the replace method makes processing the tags really easy. Once you match a set of tags, you can recursively call the parse function on that tag’s contents from inside of the function you passed to replace.

Using the parser

To use the use the parser, you’d simply include xbbcode.js and xbbcode.css files somewhere on your page (which are contained in the zip file linked above), and then call the XBBCODE object from somewhere in your JavaScript:

var result = XBBCODE.process({
    text: "Some bbcode to process here",
    removeMisalignedTags: false,
    addInLineBreaks: false
});
console.log("Errors: " + result.error);
console.dir(result.errorQueue);
console.log(result.html);// the HTML form of your BBCode

Adding new tags

To add a new tag to your BBCode, add properties to the “tags” object inside of the XBBCODE object. For example, say you wanted to add a tag called [googleit] which would change its contents into a link of its google search results. You’d implement that by adding this to the tags object:

"googleit": {
    openTag: function(params,content) {
        var website = "\"http://www.google.com/#q=" + content + '"';
        return '<a href=' + website + '>';
    },
    closeTag: function(params,content) {
        return '</a>';
    }
}

Then you could have BBCode like this: “[googleit]ta-da![/googleit]” which would be transformed into this: “<a href=”http://www.google.com/#q=ta-da!”>ta-da!</a>”

If you have any suggestions or find any bugs let me know.

“HTML5: Up and Running” Book Review

HTML5: Up and Running

I’ve read a decent number of articles on what will be new in HTML5. I’ve read up on the canvas element, localStorage, web workers, and a couple of the other elements one can use when creating Chrome Web Browser Extensions (for when I created my Typing Speed Monitor and Image Definitions for Dictionaries extensions).

However, I hadn’t really sat down and taken the time to thoroughly go through all the goodies that are planned for/coming with HTML5. So when my office mate showed me a huge pile of books he had just purchased, I saw the one titled HTML5: Up and Runningand got kind of curious. After flipping through it, I found out that its also available online for free under the title of Dive into HTML5, but I ended up ordering my own copy since I prefer to read the paper editions. However, a good number of resources are linked to, so a digital version of the book is somewhat advantageous.

Anyway, the book starts off with some history on how HTML developed. It goes through an old thread in a 1993 W3C mailing list archive, where participants were discussing the creation of image tag. Essentially no one could really agree on how it should be setup (Should it be img, icon or include? Should its properties be src or href?), and ultimately an author of Mosaic (an early web browser) decided to just use what he had initially proposed and shipped his browser with a working img tag. The point of the story is to show you that HTML isn’t this carefully crafted language, it’s based on discussion, but many of its features came about simply because a popular web browser decided to stand behind them.

The next chapter discusses how you as a developer can use the new HTML5 tags in your web pages today, and still have your site be backward compatible with older browsers. It uses a JavaScript technique to do this, however, there are a couple of ways to use the new tags and be backwards compatible, some of which you can read about here.

The rest of the book focuses on giving introductions to the various new features you’ll have access to in HTML5, specifically: the canvas element, the video tag, the geolocation API, the localStorage element, how to setup your site for offline storage, all the new form elements, and how microdata works. These discussions are all pretty good, though I especially liked the chapter on the video tag. I didn’t really know much about the different video formats going into the chapter, so it was nice to have a high level discussion on how videos are encoded. It was also interesting to have the author touch on the licensing issues of H.264 video. After reading about all the fees involved, especially those possibly coming after Dec. 31, 2015, it seems like it’d be a bad format to use as a standard.

Overall I liked the book and would recommend checking it out if you’re curious about using and playing around with the currently available features of HTML5.

Programming Trivia App

Photo By Mirko Junge

This has been on my computer for months and while it’s not completely finished, I wanted get a version up since I’m starting work on it again, so I present Programming Trivia Questions.

It’s born out of the basic idea I had for my old Programming Quiz App, which I released last year. Shortly after creating that app I realized that creating a list of good quiz questions was actually kind of hard, and expecting someone to write a full, non-goofy quiz was probably too much. However, coming up with a question or two is usually pretty easy. So I figured I’d change the app to be like a question database where questions were tagged with certain keywords, and the user could just select categories and get questions on those categories.

I’m not at that point yet, but I have a working demo with 20 questions. The next step will be to connect it up to a database (right now it’s all client side) and then to allow users to submit questions. Anyway, I figured 20 random programming-themed questions would be mildly entertaining so I figured I’d share it with you all. If you have any suggestions let me know.

Oh, one last note, my favorite JS graphing library, Plotkit, doesn’t seem like its being updated anymore (it’s a fantastic library, but the last update was in 2006). I made some modifications to it for this app (I changed how the colorscheme mechanism worked for bar charts if just one dataset was used) and am debating forking that library or using another one. If anyone has any graphing library suggestions let me know.

AAC Police Brief Analyzer

Photo By dooq

I’ve created a new Facebook app which I call Anne Arundel County Police Brief Analyzer. I noticed my local police department had a Facebook page and that they posted their police briefs to this page. The briefs all followed the same format, so I decided to see if I could parse them to grab out some statistics.

The app is pretty simple, and right now all its doing is counting the number of times the various cities in the county are mentioned in the briefing sub-headings. Basically it answers the question: “Which cities show up in the police briefs the most?” This app would probably be more helpful with population data, however, it was mostly just done as an experiment, so I probably wont go any further with it. However, I figured I’d post it up since I found it kind of interesting.

The only hitch to creating the app was that you can only grab the 25 notes from Facebook per request, at least with their JavaScript SDK. To grab more notes, you have change the “offset” parameter (also see batch requests). Example:

FB.api("/aacopd/notes", {offset: 175, limit:25}, function(response) {
    console.dir(response.data);
});

patrickgillespie.com Update

I’ve updated the cloud code at patrickgillespie.com to now use a canvas element in browsers that support it. This leads to a much smoother appearance in Chrome and a slightly better appearance in FireFox. I tried using excanvas for the IE version, but it was too choppy for what I was doing, so the IE version still uses divs.

JavaScript Parallax Scrolling Experiment

Parallax Clouds at patrickgillespie.com

There’s a neat CSS technique called “Horizontal Parallax Scrolling”, where background images will move at different horizontal speeds when the window is resized (example). It’s done by positioning several divs on top of each other and having their background-position property set to different offsets. You can read a great CSS tutorial on it here.

I thought it was kind of cool and decided to see if I could come up with a way of doing “Vertical Parallax Scrolling”. There are a lot of ways one could approach this, but I decided to go with fixed positioned divs that would move when the user scrolled the page up and down. These divs would be attached to the background and a content div would sit on top of the background which would have a z-index higher than any of these fixed positioned divs. All content for the page would go inside of this content div. I figured this approach would suit me well since I was thinking of creating something where there’d be lots of floating objects in the background.

After playing around a bit I came up with something that worked reasonably well in IE7+, Firefox and Safari, and ok-ish in Chrome. The effect was neat and 3D-ish, so I decided to use it at patrickgillespie.com. It replaces the silly CD cover experiment I’d previously hosted there. The effect is still not as smooth as I’d like it, but I think for a really nice smoothness I’d probably have to use a canvas element instead of a bunch of divs. Anyway, if you’re interested, I’ve put together an example which you can download here.

Website Showdown!

Photo By fPat Murray

I’ve created a new web app that lets you pit two groups of websites against each other to see which group is more popular on Facebook. It’s called Website Showdown! and works by using the Facebook API to read the number of “Shares”, “Likes”, and “Comments” a particular URL has gotten on Facebook. Whichever group has the highest count, wins.

Also, when comparing URLs, the exact URL counts. “http://patorjk.com/” wont reference all of the times something from “patorjk.com” has been shared, only the number of times that particular URL has been shared. Trailing slashes (/) also seem to matter.

The data displayed in the app is read from Facebook’s link_stat table. I may end up adding other Social Media stats to the results, but I’ll wait to see if there’s any feedback on this app first.

The Facebook API is actually kind of fun. I’ve avoided it since I’d heard some bad things, but I had no issues with it (however, this is probably the most basic type of app one can create). I’ll probably tinker around with it some more, though as of late I’ve got a lot of unfinished projects on my plate.

Below you can see a screen cap of some results. If you find any bugs in the app please let me know.

Google vs Facebook

App URL: Website Showdown!

“JavaScript Patterns” Book Review

JavaScript Patterns

I went on my honeymoon recently and decided to pick up some reading for the plane ride*. The book JavaScript Patterns** piqued my interest after seeing it on this list of useful JavaScript books, so I decided to check it out.

The book’s aim is to provide useful techniques and abstractions (coding patterns), best practices, and approaches for implementing popular design patterns for the mid-level to advanced JavaScript developer. However, its main focus is on coding patterns. After introducing JavaScript and going over some basic concepts, the author launches into a chapter on best practices, which covers a grab bag of topics, everything from naming conventions to loop optimization to writing API docs. This chapter was actually where I first learned of YUIDoc and JSDoc, two great tools for generating API documentation for JavaScript code.

After that follow the chapters on coding patterns. The author goes over various subjects and explains techniques that will make you a better developer. Techniques like enforcing new when you define constructor function, the module pattern, self-defining functions, etc. Some of it you may already know, but it’s a good collection coding patterns.

The book finishes up with a chapter on implementing common design patterns in JavaScript (it covers: Singleton, Factory, Iterator, Decorator, Strategy, Facade, Proxy, Mediator, and Observer) and a chapter on working with the DOM. If your main interest is in learning design patterns, I’d probably recommend Pro JavaScript Design Patterns instead, since it’s main focus is design patterns and it devotes more time to explaining them and giving examples, however, if you’re already somewhat familiar with them and you have a decent understanding of how OOP works in JavaScript, than I would pick this book up instead as it cover more ground and is faster paced.

Overall I really enjoyed this book and learned a lot of useful tid bits from it. I’d recommend picking it up if you’re looking write better JavaScript code and to fine tune the techniques you know about JavaScript.

* The other books I read were Fahrenheit 451 (it was ok) and The Martian Chronicles (excellent book).
** Non-referral link, just so you all don’t think I’m trying to sell you books.

Snake Game Update

You can play snake in the box below.


I decided to redo the internals of my JavaScript Snake Game since it was old and in dire need of an update. I thought about using the canvas element, but since it still has its issues with IE and excanvas can be a little slow, I decided to stick with using divs for the drawing blocks. The game is probably not the best it could be, but it’s definitely better than where it was at. If you’re interested in the inner workings I have the source available here.

Documentation Page Example

For this update I also decided to experiment a little with YUI Doc, which is a tool that generates documentation for source code. It caught my eye since it creates beautiful looking documentation and it’s language agnostic, so it could possibly be used for all sorts of projects. The documentation for this Snake game probably isn’t too useful, but on larger projects I could definitely see this kind of thing coming in handy.

The only negative to the tool was that it didn’t seem well documented itself. I found myself somewhat frustrated in debugging some of the issues I had using it, and I ended up having to do a little hand editing of the output files to remove YUI Library labels. Other than that though, it was a pretty cool tool.

ASCII Art Code Comments

Nick Kaye emailed me yesterday suggesting I add a feature to the Text ASCII Art Generator program which would allow for the output to be formatted in the form of a C-style programming comment. He even offered to write the code patch himself.

I thought the idea was really cool, and took him up on his offer. Anyway, the new feature is under the “More Options” link in the TAAG interface. Once it’s turned on, you’ll get output that’s formatted in the form of a programming comment. Here is an example:

/***
 *                      .___       
 *      ____   ____   __| _/ ____  
 *    _/ ___\ /  _ \ / __ |_/ __ \ 
 *    \  \___(  <_> ) /_/ |\  ___/ 
 *     \___  >\____/\____ | \___  >
 *         \/            \/     \/ 
 */

If anyone has any issues or additional suggestions let me know. And thanks again to Nick!