Posted 11.25.2009

Updated 02.28.2015

Writing jQuery Plugins (Part 1)

The more I write code, the more I realize how repetitive it is. It’s more cost effective (and brain-thawing), if you can figure out ways to be reuse your code. A few weeks ago, I started trying to figure out how to write my own jQuery plugins. Granted, you can probably find an existing plugin for anything that catches your fancy, however, a lot of times, the footprints are larger than necessary to accommodate more people. Besides, I’ll usually find one effect and stick to it (personal preference), rendering most of the customization in the plugin useless. At this point, it becomes easier to write my own code.


EXISTING JQUERY PLUGIN TUTORIALS

Here are a few sites that I looked at to help me get a grasp on structure. As most things, some are better than others. The hard part is some people assume you know more or less, leaving you to put the pieces together. My goal, in this post, is to the heavy lifting for you.


First things First

I’m gonna assume that you’ve at least heard of jQuery. If not, the elevator pitch? It’s a framework for JavaScript. In my humble opinion, it’s far easier to understand and much easier to write than JavaScript. If you’re a web developer, it’s definitely something worth checking out. I’d start by visiting the jQuery site or I’ve listed a few books (yes, you read that correctly, books) at the bottom of this post.


Captain Obvious

The first thing you’ll need to do is download the jQuery library. This has to be included on your page before any jQuery code can be written.

<script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> 

Update February 28, 2015

One of the things I prefer to do is use Google’s CDN version of jQuery. Several reasons:

  • It prevents me from having to download the code and store it on my server.
  • If your user has visited another site that is using Google’s CDN version of jQuery, then their computer will cache the code on their computer. Then, when that same user visits your site, the code is already cached and it’s one less thing they will need to download to get your site to load.

Instead of using the above line, you can use this instead:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Digging In

File Naming Structure

Your file should always be called jquery.your_plugin_name.js. Obviously, your_plugin_name will be unique to your plugin.


Documentation

Yes, documenting your code is a pain. However, I promise, when you come back to your code, months later, it more than pays off. The code that you say (and wish) you will never come back to will inevitably haunt you. (can you hear the agony of experience in my voice?) :-) Besides, plugins are meant to be reused.

At the top of my file, I list out the name of the plugin, the date that I wrote it, the author (me!), my url, requirements, and implementation.

/* ==================================================================
*
*    ROLLOVERS PLUGIN
* 
*    DATE:                 FEBRUARY 28, 2015
*    AUTHOR:             AMY HAYWOOD
*     URL:                 WWW.AMYHAYWOOD.COM
*
*    REQUIREMENTS:         jQuery
*                        Be sure to include the jQuery library before including this script
*     IMPLEMENTATION:
*        Within the $(document).ready(); all that you really need to include is:
*        |    $('.CLASS_NAME_FOR_ROLLOVER').rollover();
*        
*        Within your HTML, be sure to give the image, use the same classname that you used to call .rollover()
*        Within the rel attribute, include the path to the rollover image
*        |    
*
===================================================================== */

Code within your plugin

Basically, every plugin that you will write, will have the following code in it.


(function($) {
    $.fn.rollover = function(options){
        // DEFINE OPTIONS
        var defaults = {};

        var settings = $.extend(defaults, options);

        return this.each(function() {

        });
    };
})(jQuery); 

Let’s take a step back…


A QUICK EXAMPLE :: ROLLOVERS

THE LOGIC

  • I want to have an image with the file path of the rollover in the rel attribute.
  • When the user rolls over the image, it is swapped out with the value provided in the rel attribute.
  • When the user rolls off the image, it is swapped back to the original image.

Easy enough?


IF I WAS WRITING THE CODE FOR 1 SITE

If I didn’t plan on using this code again, I would simply put the following code in the $(document).ready(); code in my header.


$(document).ready(function() {
    
    $('img[rel]').each(function() {
        var curImg = $(this);
        
        // GET THE VALUES
        var defaultImage = $(curImg).attr('src');
        var rolloverImage = $(curImg).attr('rel');
        
        // SET UP THE ROLLOVER BEHAVIOR
        $(curImg).hover(function() {
            $(curImg).attr('src', defaultImage);
        }, function() {
            $(curImg).attr('src', rolloverImage);
        });
    });
});

Too much too fast? No worries. I’ll break it down.

When you write jQuery code, most of it will appear within $(document).ready();. Basically, it waits until all the pieces on your web page have loaded and are available.

In this example, if we tried to find all the images before they had even loaded, it would return nothing!


$('img[rel]'.each(function() { 

This line of code looks for every image with a rel attribute. For EACH item, it will grab the current image src $(curImg).attr(‘src’) and save it as defaultImage. Then, it will grab the path for the rollover image $(curImg).attr(‘rel’) and save that as rolloverImage.

Lastly, it will set up the behavior. The hover function takes two parameters. The first, will determine what happens when you rollover the item and the second parameter will determine what happens when you roll off. In this case, it’s just a matter of setting the img src based on the defaultImage and rolloverImage.


MAKING THE CODE RESUABLE

Basically, we take the code that we would have made for 1 site and plug it into our jQuery plugin structure. The hardest part is just making sure we abstract everything (a.k.a. make it generic enough so that we can use it over and over).


(function($) {
    $.fn.rollover = function(options){
        // DEFINE OPTIONS
        var defaults = {};

        var settings = $.extend(defaults, options);

        return this.each(function() {
            var $element = $(this);
            var defaultImage = $element.attr('src');

            $element.hover(function() {
                $element.attr('src',  $element.attr('rel'));
            }, function() {
                $element.attr('src', defaultImage);
            });

        });
    };
})(jQuery); 

The only thing that I changed was I took out the code that was in the .each() function (from my 1 site code) and placed it within the this.each(function() { }); of the plugin. Now, when I call the plugin, it will run the loop on all the items I pass to it.

So, in the header of my HTML file, it will look like this:


<header>
    <title>JQUERY ROLLOVER TEST</title>
    
    <!-- LINK JAVASCRIPT FILES -->
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery.rollovers.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
            // INITIALIZE PLUGIN
            $('.CLASS_NAME_FOR_ROLLOVER').rollover(); 
        });
    </script>
</header> 

Now, for every item in the body that has a class name of .CLASS_NAME_FOR_ROLLOVER it will try and create a rollover.


Stay Tuned

This post would probably fit into the “assuming you know less” category. On Friday, I’ll take a more in depth look at plugins, demonstrating their extensibility (i.e. setting preferences). Just to whet your appetite, we’ll be building an image rotator where you can pass in the speed.

Download My Code

jquery.rollovers.js (kB)


CALL ME OLD FASHIONED

Call me old fashioned, but I still enjoy reading programming books. I know, ancient. I love my Kindle, but there is still something to be said for flipping pages, laying out multiple books, and cross-referencing. With that said, my favorite jQuery resources are books. That’s how I taught myself.


Learning jQuery
This is the book that I used to teach myself jQuery.


jQuery Reference
This book is also published by Pakt Publishing. This is the book that I go to for reference.


jQuery in Action
Yes, the cover looks a little hokey, but some of the content in the appendixes is worth the book’s weight in gold.

 



Posted 11.16.2009

Posted 11.16.2009

CMS Comparison: Choosing the Right Tools to Power Your Blog

I’m a HUGE fan of Expression Engine. (Actually, I love all the stuff that Ellis Labs is doing). However, as I’ve worked on other projects that require a different platform, I’ve had the “opportunity” to learn.

Movable Type



At my day job, I’ve been building (a lot of) blogs on Movable Type’s platform.

BUSINESS CASES FOR MOVABLE TYPE
My friends in high places (i.e. IT) tell me that Movable Type was chosen because of the support that they offer. If WordPress goes down, you’re SOL. However, Movable Type offers customer service that will help you solve the problem. In fact, I assume that’s one of the reasons why Obama is using Movable Type.

Also, from a multi-author platform, Movable Type is easy peasy, lemon squeezy. Literally, a few clicks and you’ve got another blog up and running.

The Community
At first, I HATED Movable Type, namely, because of the (lack of) community. There was a HUGE change in the code between version 3 and 4. A quick Google search of “Movable Type Tutorials” has 746,000 hits, however, I wouldn’t be surprised if 90% of the results are based on old code = USELESS.

It’s amazing what community support does.

  • Plugins – Because the community so small, there aren’t very many plugins to choose from
  • Knowledge: Tutorials, Best Practices, + Troubleshooting – Whenever I run into an issue, my best bet is to phone a friend. There aren’t a whole lot of other resources out there, unfortunately.

DOCUMENTATION
I haven’t been impressed with the documentation on Movable Type’s site either. It’s hard to find the information that I need, and in some cases, the documentation that I have read has been inaccurate! Talk about beating your head against a wall!

TEMPLATING PROCESS
Once you understand the templating process, it’s actually not THAT bad. But there are a few key concepts to remember. For example, Movable Type is based on PERL. –SO– when you write a blog post, it will actually generate a static HTML page. The cool part is this makes your site super fast. It’s not having to ping the database every time a user visits a page. Even if you have a whirl wind of traffic, Movable Type can handle it better than some of these other CMSes. However, every time you make a change to a template, you’ve got to republish your site, especially on pages with includes (header, footer, sidebar, etc). This makes minor site tweaks incredibly tedious.

Quick Note:
I’m planning on writing a series about building sites in Movable Type, so please be patient and stay tuned.

TEACHING OTHERS TO USE MOVABLE TYPE
It’s also proved a challenge teaching others how to use Movable Type. It’s not that difficult, but when someone is used to WordPress… well, there’s enough difference to cause some aggravation.


WordPress


I’ve been working a freelance project for the Cooperative Program. We decided to go with WordPress for a couple of reasons:

  • Custom Fields
  • Cost (free)
  • There’s a plugin available for just about anything
You can create custom fields in Movable Type, however, it requires a special plugin.

THE DIFFERENCE BETWEEN WORDPRESS .COM AND .ORG
WordPress.com is hosted on WordPress’s site. The nice thing: you can have an account + blog ready to go in 5 minutes flat. The downside? there are a few restrictions on which plugins, themes, and backend hackery you can do. For a control freak like me (when it comes to code), this isn’t acceptable. I lean towards WordPress.org.

WordPress.org means that you download WordPress and install it on your own server. You’ll have to go through a service like GoDaddy or Network Solutions.

Over your head?
When you create a website you have to have a name and a place to store it. Think about it like this. When I buy a house, I have to have an address and a plot of land. Same thing for the web: an address (http://www.amyhaywood.com) and a place to keep all my files (Network Solutions or GoDaddy).

THE WORDPRESS COMMUNITY
Unlike Movable Type, the community is HUGE. This is fantastic when you’re trying to troubleshoot or find a specific plugin. Chances are, someone’s already figured it out.

Like most things in life, the pendulum swings both ways. If Movable Type = non existent, then WordPress = over saturated.

For every question there are dozens of solutions. I struggle with finding the best practice. Every plugin installs and places its preferences somewhere different. If I have a dozen plugins, then my backend ends up looking junky. –There are no standards!

When I’m Googling “creating custom themes for WordPress”, there are tons of tutorials out there, but some glaze the surface, while others go way too deep.

As much as I complained about Movable Type, I would choose it over WordPress.

I’m planning on writing a WordPress tutorial of my own, so, again, patience please!

Tumblr


My boss uses tumblr and loves it. We’ve implemented it at work, for sharing cool things that we find (either resources or inspiration for upcoming projects). So far, it’s worked out pretty well. If a new post has been made, I’ll get an Email every morning with the new content. This is nice. It’s not updated regularly, I don’t have constantly visit the site to check for new posts. (Actually, that feature specific to Tumblr. That was done with the help of Feedburner.)

THE COMMUNITY
Tumblr is all about the community. You can follow people within Tumblr and easily repost content, if someone has already posted it once on Tumblr.

Funny, though, you can’t comment on posts that people make, unless you hack it, with Disqus

SIMPLICITY
There are only 7 types of content that you can post to Tumblr: text, photo, quote, link, chat, audio, and video. Again, pretty straight forward, but not enough to support a complex site.


Expression Engine



This is my favorite. Hands down. I’m bias.

Documentation
Expression Engine’s (EE) documentation is well written: complete, easy to understand, and easy to navigate.

THE COMMUNITY
The community is so great. Anytime I have had an issue and posted it on the forums, I’ve generally had a response with a few hours.

The plugins that have been created are quality.

— With EE2.0 they’re building it on CodeIgniter’s framework, which will make it even easier to build plugins.

There are plenty of tutorial sites out there that have great information. If you’re just starting, I would suggest starting with Pragmatic Programmer. However, EEInsider, DevotEE, Jambor-EE, TrainEE, and EE How To are also good resources worth visiting.

CLIENT ADOPTION
I’ve trained multiple clients on using EE. In all cases, (even non-Tech clients) have been thrilled with how easy it is to update their site.

FREEDOM + FLIEXIBILITY
EE’s greatest asset is it’s flexibility. I can do anything. I LOVE having complete control over my code. No limitations.

Yeah, the flipside is that I have to code more, but in the end, I’m so much more pleased with results.

THE FUTURE
They recently announced that version 2.0 will launch December 1, 2009. After waiting a year and half, you can bet I did a happy dance and marked it on my calendar. (and you think I’m joking)


SQUARESPACE



While I’ve been getting antsy for EE2.0. Darrel also loves SquareSpace. He’s using it to run another one of his blogs.

TEMPLATING
So, I’ve been experimenting, a little. My biggest beef (again) is control. It’s super easy to change your templates and add new widgets, however, creating custom templates is another story. I have a decent amount of control through the CSS, but some of it is hack-y. For example, to move the menu above the header: margin-top: -200px;

I also can’t insert HTML. Take my website for example. I have a vignette in the top left and right corners. Ideally, I need 2 containers that will span 100% with absolute positioning. With the given structure from SquareSpace, I can only get 1 corner to work.

Even though, EE is by far my favorite, I would consider “selling” a client on SquareSpace.

One thing that SquareSpace has that EE doesn’t: an iPhone app. We’ll see what happens after December 1…



Posted 11.14.2009

Planning a Web App

Lately, I’ve been working on a super secret project. (details to come later…yeah, I hate that line too)

So far, it’s been a great learning experience. I’ve been coding on Code Igniter, which for someone that L-O-V-E-S Expression Engine, Code Igniter is even better.

One of the things that I’ve been struggling with is how to plan out a web app.

I’ve read (most of) 37 Signal‘s book, Getting Real, which talks about just doing it:

Don’t write a functional specifications document

These blueprint docs usually wind up having almost nothing to do with the finished product. Here’s why:

  • Functional specs are fantasies
  • Functional specs are about appeasement
  • Functional specs only lead to an illusion of agreement
  • Functional specs force you to make the most important decisions when you have the least information
  • Functional specs lead to feature overload
  • Functional specs don’t let you evolve, change,and reassess

When you’re anxious to get a project off the ground, this is a great method. I made huge headway at the beginning of the project. I impressed myself, even. However, I eventually had to take a step back. There were a few problems:

  • I kept changing my code because I had not made all the decisions up front on how something was going to work.
  • I started to get this fear in the pit of my stomach that my code was not efficient. I was duplicating code because I hadn’t thought through it on the front end.
  • I hit a wall. There wasn’t a clear next action step. (thanks GTD)

Back in September, Ryan (37 Signals employee) wrote a blog post, A Shorthand for Designing UI Flows. I’ve tried using this to press on, but it’s still hard. My charts look overwhelming.

What is the best practice? Thoughts? Suggestions? Resources? Musical Anecdotes?