jQuery || plugin

20090908842

I use this pattern a lot in javascript to set a default for a variable inside a function depending on whether or not an argument was passed in:


var obj = el || window;

It’s handy, quick, concise and feels slightly clever.

I sometimes have a need for something similar while manipulating jQuery objects. But because jQuery always returns an object, perhaps empty, but an object no less, simple compares don’t work. Length must be checked. To achieve something similar to the pattern about, you’d need to do a full ternary statement, either as the selector or to set a result to a variable and go from there:


$($(".trythis").length ? $(".trythis") : $(".default")).chain…;

That starts getting hard to read, but says if there are any elements with the class “trythis”, get them and continue doing stuff to them. Otherwise, get elements with class “default” instead and do the stuff to them.

Plugin or custom selector

Initially I had hopes of using jQuery’s facility for expanding selectors to make an “or” condition work within the selector. Unfortunately, and reasonably, that didn’t work out because if the first part returns nothing, the custom test never executes. Furthermore, it only returns boolean and doesn’t allow for switching out the returned jQuery object.

So plugin it is:


jQuery.fn.or = function(s) {
  return $(this).length ? $(this) : $(s);
};

Allows for:


$(".trythis").or(".default").chain…;

Significantly more clear than the example above. Unfortunate the double pipes won’t work but perhaps “or” is more fitting anyway considering the existing “is” and “not” methods.


Skateboards and bikes are better at nights

Skateboards and bikes are better at nights. 0 comments.


Search WayTooCrowded
The Header Should Always Point Home