Here’s a kind of silly mistake I made the other day. (I made a mistake! Gasp!) It’s easy to make. Fortunately also easy to fix.

I needed a little Javascript/jQuery snippet to target images within a certain element class, lets call it <div class="target">.

So I had written this:

  function init () {
    attachImageHooks();
    listenForMoreRepeaters();
    ...
  }

So attachImageHooks() attaches some event hooks to $('.target') and the rest relies on the image hooks being there.

The problem is, sometimes the target is on the page, and sometimes it’s not. When it’s not, there are no hooks and then things break farther down.

The fix is easy. Just check for target first and if it’s not there call the whole thing off.

  function init () {
    if( 0 === $('.target').length ) {
      return;
    }

    attachImageHooks();
    listenForMoreRepeaters();
    redirectOnSubmit();
  }

More often than not with code, it’s the little things, things easily fixed but ignored as not important, that cause the unexpected disruption.

Quick Tip: When things are breaking, check your assumptions about the conditions before you try to do the thing that breaks.