Category Archives: JavaScript

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.

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.

“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.

“JavaScript: The Good Parts” Book Review

JavaScript: The Good Parts

JavaScript: The Good Parts

Last month I finished reading the short but densely packed JavaScript book JavaScript: The Good Parts.I had been looking for a book that would cover some of the pitfalls of the language more thoroughly than what I’d read about previously and when I saw this in the bookstore it seemed to fit the bill.

The thesis of the book is that JavaScript is a misunderstood language. It recognizes that there are bad parts to the language, but it contends that once you get past them there are some pretty nice good parts – and that by using only the good parts and avoiding the bad parts, you can write some really great code.

The book covers objects, functions, arrays, regular expressions, closure, and how inheritance works in JavaScript. The last one is probably the most important, since most people are only familiar with classical inheritance, and JavaScript’s prototypal inheritance, although wrapped in a syntax that makes it look classical, is very different. The book also discusses JavaScript’s bad parts and why you should avoid them.

Most of the concepts in the book are well explained, though I did find myself needing to re-read certain sections twice to completely understand the topic. This is in part because the book is very short, coming in at 153 pages (including the index). This is a double edged sword in that it allows you to take in a lot of material in a short amount of time, but sometimes you’re left wishing that a little more time was spent on a certain topic.

One other possible fault with the book (depending on how you look at things) is that it does not cover the DOM at all. The DOM isn’t part of the JavaScript language, but almost everyone who uses JavaScript will need to interact with the DOM. Therefore, this book is really more of a companion piece than a definitive reference for JavaScript programming.

Overall I really liked this book. It gives good coverage to some important topics regarding objects and functions, and gives a good explanation of prototypal inheritance. A lot of language quarks are also pointed out and explained. For example, one thing I didn’t realize was that the arguments array that is implicitly passed to functions isn’t a real array. It’s just an object with a length property. The appendix sections covering the “bad parts” and “awful parts” were also pretty interesting, though I disagree with the author that ++ and — are bad.

Anyway, I highly recommend the book if you’re into JavaScript programming. It’s a nice easy read that covers a lot of ground. Also, this is a non-solicited review, though the link above is an amazon referral link.

If you’re interested, the book’s author gave a one hour talk on this book that touches on a lot of its ideas. You can watch it here (actual talk starts at 2 minutes 15 seconds):

Playing Around With HTML5’s Canvas Element

After reading up a on HTML5’s canvas element, I decided to re-tool the game I was working on to work inside of a canvas element. This was because the canvas element provides some great drawing functionality. You can resize, rotate, crop, position and alter the pixels of images you use on the canvas.

FireFox

FireFox Appears to Have the Best Support for the Canvas Element
Photo By M i x y

The game is still not done, however, I’ve uploaded another demo that shows the space ship and its main bad guy. You can use the arrow keys for movement and the “s” key to shoot. I changed the shoot key from the Space Bar to “s” because Opera was giving me issues when the Space Bar was pressed while the canvas had the focus.

Also, unlike last time, the game works best in FireFox, and basically sucks in everything else. Opera and Chrome can run the demo, but the frame rate is painfully slow. Since IE doesn’t support the canvas element yet, I’m using the JavaScript library Explorer Canvas to emulate it. Though you have to be using IE8 and be in “Quirks Mode” for it to work – and even then, the game is unplayably slow. Since the canvas element is part of the new standard, and one of its hyped uses is for creating games, I’m assuming / hoping that its performance is going to improve over the next couple of months in these browsers. However, since the canvas element is so cool, I’m still going to finish this game off even if it only works in FireFox.

For those of you interested in using the canvas element, Mozilla has a really good tutorial on it here, and there are some neat canvas game-themed tutorials here.

Lastly, and on a completely different note, I’ve written an update to the Is Someone Pretending To Be You Online? post I made a year ago. The update is at the bottom of the post and basically says the problem was due to a database error (which was a relief). I didn’t do an update right away since I didn’t want to embarrass the site owner.

Creating a JavaScript Space Ship Game

“What would be something neat to do in JavaScript?” – I kept asking myself that on Saturday. My fiance was away for the weekend and I was just kind of hanging out at home with the dog. Eventually I ended up thinking about possibly trying to do a side scroller game, like Mario Bros or Commander Keen, but since I had never written one before, I wasn’t sure. Finally, I came to the conclusion that it might be wiser to go for something a little easier first, and decided it might be cool to port my old “Intergalactic Odyssey” space ship game to JavaScript.

Old Intergalactic Oddyssey Game

Old Intergalactic Oddyssey Game

My goals here were to just see how feasible it would be to create an action game with moving sprites. I didn’t get very far, but I was able to create a space ship that could fly around and shoot lasers. I was able to get the graphics by decompiling my old SWF Flash file (I’ve long lost the source to the game). Also, the space ship artwork was done by fitz. I originally found the space ship via Google Images, though I did ask before I used it.

So far the main issue I’ve run into is that IE and FireFox aren’t reliable for smooth game play. The demo works best in Google’s Chrome and Opera’s Opera web browser. Though at this point I haven’t added any collision detection in, or any bad guys in, so there’s still a ways to go before I know if I’ll have a playable game.

One thing I didn’t realize when I started was that I could rotate images. I googled for a little bit and didn’t come up with anything, so I wound up creating images for each of the different rotations of the space ship. Though now that I’ve read up on it a little more, image rotation can apparently be done with the Canvas object in FF, Opera and Chrome, and with filters in IE. I suppose I’ll find out later which method is faster.

Lastly, the key capturing events are a little frustrating, since JavaScript doesn’t appear to remember when someone is holding the Up-arrow down if another key is pressed while its down. I’m still trying to figure out if there’s a way to get around this.

If you have any tips/suggestions, feel free to let me know.

My First Try At Revamping My Typing Speed Test

I’ve just updated my Typing Speed Test. I basically just implemented the changes that people suggested to me. These included:

  • Allowing the user to type real sentences, for example, stuff from books.
  • Adding more text input options.
  • Cutting the default time down from 60 seconds to 30 seconds.
  • Not having the text scroll as the user types and letting the user see all of the text they will have to type.
  • Highlighting of the correct, incorrect, and the current word in the box displaying the text that needs to be typed.
  • Providing obvious instructions on what to do.

I was unsure about how to display the instructions, so I just put a yellow information box at the top of the page. The only other thing I could think of was to start the app with a Ext JS-style message box, but I figured that would get really old after a while. Also, the spacing at the bottom of the page is kind of weird because I wanted the tab sizes to be static. I’m not sure if that’s the best design idea, so that may change.

A possible visualization indicating which keys were typed fastest

A possible visualization indicating which keys were typed fastest

For the next release, I’m thinking about adding in more stats on how fast the user types. Maybe giving them info on what keys they typed fastest via a visualization or some bar charts. A line graph showing their progress over time might also be cool. However, JavaScript may not be fast enough to let me do this. While beta testing today I noticed that sometimes I almost got ahead of the app, and keeping lots of extra stats may slow things down too much, I’ll have to see though.

Thank you to those of you who gave me suggestions. I think the test is much, much better now.

If anyone has any more suggestions or finds any problems please let me know!

Oh, and one last news worthy item, I also updated the About page on this blog with some more info and pictures.

“Learning Ext JS” Book Review

Learning Ext JS

Learning Ext JS's Book Cover

This will probably be my last book review for a while. In December I said I wanted to do some more reading up on JavaScript and I think I’ve satisfied that itch. I’ve read 3 and a half books on the topic since then and I think I’ve gained a good amount of knowledge on the language and some of its various frameworks.

This latest book was sent to me by Packt Publishing (in exchange for a review giving my opinion on the book) and covered the Ext JS framework. Its name is Learning Ext JS and its authors are Shea Frederick, Colin Ramsay, and Steve ‘Cutter’ Blades.

Ext JS is a JavaScript framework that’s known for the eye catching user interfaces that it helps you create. It’s geared toward web application development and it was originally written as an extension to the Yahoo User Interface (YUI) library. Unlike many of the other JavaScript frameworks which are offered under permissive licenses, Ext JS is only available via the GPL, a reseller license, or a commerial license.

Learning Ext JS is a good book and I enjoyed reading it. It has a similar set up to the other Packt Publishing book I read on Dojo, however, Shea and company take a little more time to explain things, which results in a longer but better quality book. I especially liked the first few chapters since the examples were easy to follow and involved a little humor. I also liked how a lot of attention was given to grid widgets (two whole chapters). This is an especially useful widget and it’s not usually obvious how to use or set them up.

As for the flow of the book, it starts off by showing you how to get Ext JS up and running and then it walks you through a small, mostly dialog-based application. After the sample app, the book proceeds with chapters that cover a particular area of the framework – Forms, Buttons/Menus/Toolbars, Grids, Layouts, Trees, Windows and Dialogs, Effects, Drag and Drop, and Data. The last two chapters of the book are on extending the framework and on some odds and ends of the framework (like various widgets created by community members).

The book is aimed web application developers who are familiar with HTML but who may not have any experience with JavaScript. However, even though the authors hold your hand through the early chapters and give an explanation of Object-Oriented Programming in one of the later chapters, this book should really only be read by people who are familiar with JavaScript. I can’t see someone without any JavaScript experience being able to tackle a framework like this.

So if you don’t have much experience with JavaScript, I’d probably pick up a book on plain old JavaScript first. However, if you’re interested in a book on Ext JS and have some JavaScript experience, I’d recommend this book. It provides a good introduction to the framework and takes you through many of its different areas.

Also, for those of you interested in a sample chapter, Packt has Chapter 7: Layouts of the book online in pdf format. Personally I think letting a user read the first and second chapter would be much more useful, but a sample chapter is better than no sample chapter.

Looking Into Ext JS

Packt Publishing, the same book publishing company that sent me the Dojo book, has offered me another free book in exchange for a review, this time on the JavaScript framework Ext JS. I don’t consider myself an expert book reviewer, however, it sounded like another a great opportunity/excuse to learn something new, so I took them up on it.

The book is titled Learning Ext JS and is written by Shea Frederick, Steve ‘Cutter’ Blades, and Colin Ramsay. So far I’ve read about 60 pages, and it’s looking like it’s going to be a pretty good book. It’s paced well and the authors seem to have a good sense of humor (they introduce Ext JS message boxes using a character from Office Space), though I still have around 190 pages left, so there’s still a long way to go.

Example Ext JS Message Box

Example Ext JS Message Box

Ext JS doesn’t appear to be too different from other JavaScript frameworks I’ve tried, though its main focus seems to be in creating slick looking web interfaces. It was originally created as an extension to the Yahoo User Interface (YUI) library, however, due to its popularity, it ended up growing into a stand alone JavaScript framework. Since it was developed with YUI in mind, it initially required YUI to be present to do the behind the scenes work. This changed over time, first with adapters being written so other frameworks (like jQuery and Prototype) could be used to do the core functionality, and then later so that Ext JS came as a complete, stand alone product. Though during this last phase they did keep the hooks in so that you could still use an adapter and have another framework to do the behind the scenes work if you wanted.

From what I’ve seen of Ext JS so far, it’s looks pretty impressive. The offical
Feed Reader and Web Desktop sample apps look especially cool. The only negative I can see, which was initially pointed out to me by Sloat, is that license for the library is the GPL. This means that apps you write using it would be under the GPL and you would have to release the code for them under the GPL. You can avoid doing this by purchasing a commercial license, though this would cost you between $289 and $18,699, depending on the license and support options you picked.

Knowing this, I probably wouldn’t write any large applications using Ext JS, unless I planned to purchased a license. However, for most of the stuff I write, I don’t mind the source code being available, so having to use the GPL is annoying but not a deal breaker. This is something you should think about before you decide to use the Ext JS library though, because this license requires that you release your source code under the GPL.

Anyway, hopefully this experience will lead me to learning a couple of new tricks and being able to create some nicer looking apps. Instead of waiting until I finish the book to do any kind of in depth work with the framework, I think I’m going to try and be a little more interactive this time and write stuff as I go. That way I don’t end up ignoring this site.