jQuery Misc plugins

|

This page contains a collection of minor jQuery plugins which are too small, too simple, or just not exciting enough to require individual pages. More will be added as I find the time… and the code!

These once-misc plugins have been “promoted” to full projects:

Note for non-jQuery users

For plugins that are marked “jQuery is optional” please note that jQuery isn’t actually required for the plugin to work, because nothing internal uses any jQuery methods or properties. jQuery is just used as a namespace under which the plugin’s methods can exist.

Since jQuery isn’t actually required for the plugin, if jQuery doesn’t exist when this plugin is loaded, the plugin’s methods will be created in the Cowboy namespace. Usage will be exactly the same, but instead of $.method() or jQuery.method(), you’ll need to use Cowboy.method().

jQuery :attached, :detached selectors

Selectors that match elements currently attached to or detached from the DOM.

Usage example:

var elem = $('div');

elem.filter(':attached').addClass( 'foo' ); // all divs get the class
elem.eq(0).is(':detached'); // false

elem.detach();

elem.filter(':attached').addClass( 'bar' ); // no divs get the class
elem.eq(0).is(':detached'); // true

jQuery each2

When you need to do $(this) inside an .each loop iterating over many thousands of elements, you could use this plugin instead of .each, because it has been specifically optimized for this use case.

Inside the .each2 callback, while this is still the DOM element and that element’s index is still the first function argument, the second argument is a jQuery object referencing the single DOM element, which is functionally equivalent to using $(this), but a whole lot faster.

Note: if you don’t need $(this) inside the callback, the core jQuery .each method will be significantly faster. Also, if you’re not trying to super-ultra-hyper-optimize performance, this plugin is probably not going to make a huge difference to you. Inspired by James Padolsey’s quickEach.

Usage example:

// jQuery each2 plugin usage:
$('a').each2(function( i, jq ){
  this; // DOM element
  i; // DOM element index
  jq; // jQuery object
});

// jQuery core .each method usage:
$('a').each(function( i, elem ){
  this; // DOM element ( this === elem )
  i; // DOM element index
  $(this); // jQuery object
});

jQuery getClassData

If you’re not yet using HTML 5 data- attributes, you can store basic data in an element’s class attribute for easy retrieval. Just give each datum a prefix, which you can then use to select it.

Note: data can’t contain spaces, and prefix is case-sensitive.

Usage example:

// Given this HTML
// <div id="foo" class="bar-123 baz.test baz.xyz">Look, I'm a div!</div>

$('#foo').getClassData( 'bar' );      // returns '123'
$('#foo').getClassData( 'baz', '.' ); // returns 'test xyz'

jQuery getUniqueClass

For when you really need a unique classname, (like when you’re cloning a whole bunch of elements and don’t exactly know where they’re going, but need to do something with them after they’ve gotten there).

Usage example:

var c = $.getUniqueClass(); // c set to 'BA-12352576545660' or so
$('p').addClass( c );
// .. haphazardly clone a bunch of <p> elements ..
$('.' + c).removeClass( c ).doSomethingNow();

jQuery htmlDoc

Use $.htmlDoc( html ) as an alternative to $(html) when you have html, head or body tags defined in your HTML string and need to access those elements or maintain the hierarchical structure those elements provide.

Why this plugin is necessary

From the jQuery .load() API docs:

jQuery uses the browser’s .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as html, head or body elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

Using jQuery, and given this test.html:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
  <title>Test</title>
</head>
<body>
  <div id="content">
    <p>stuff</p>
    <p>more stuff</p>
  </div>
</body>
</html>

This behavior can be seen:

$.get( 'test.html', function( html ) {
  // In doing this, the browser removes the HTML, HEAD and BODY elements
  // which results in the loss of part of the hierarchical structure of the
  // document.
  var h = $(html);

  // Not great: [, <title> Test </title>, , <div id="content">...</div>, ]
  console.log( h );

  // This fails: []
  console.log( h.find( 'body' ) );

  // This fails too: []
  console.log( h.find( '#content' ) );

  // This selects the content div, but it's ugly and not generic.
  console.log( h.filter( '#content' ) );

  // This also selects the content div, but it's also ugly, and won't work
  // for HTML, HEAD or BODY elements.
  console.log( $('<div/>').html( html ).find( '#content' ) );
});

Using this plugin, things works more like you’d expect them to:

$.get( 'test.html', function( html ) {
  // Since placeholders are used when rendering, and once done, placeholders
  // are systematically replaced with the corresponding HTML, HEAD and BODY
  // elements, the hierarchical structure of the document is preserved.
  var hd = $.htmlDoc( html );

  console.log( hd.filter( 'html' ).length ); // 1
  console.log( hd.filter( 'html' ).attr( 'lang' ) ); // "en-US"
  console.log( hd.find( 'head' ).length ); // 1
  console.log( hd.find( 'body' ).length ); // 1
});

jQuery isjQuery

Determine if an object reference is a jQuery object.

Since every jQuery object has a .jquery property, it’s usually safe to test the existence of that property. Of course, this only works as long as you know that any non-jQuery object you might be testing has no .jquery property. So.. what do you do when you need to test an external object whose properties you don’t know?

If you currently use instanceof, read this Ajaxian article.

Usage example:

function doSomething( obj ) {
  if ( $.isjQuery( obj ) ) {
    obj.somejQueryMethod();
  } else {
    nonjQueryMethod( obj );
  }
}

jQuery loadAdScript

Load third party ad network scripts that use document.write into specific containers.

The only downside is that the ads will load serially.. but that’s necessary to keep them from stepping on each others’ toes. And the upside is that your site isn’t completely borked!

Usage example:

$('#ad1').loadAdScript( 'http://adnetwork.com/horrible_ad_1.js', function(){
  // This optional callback executes when the script has fully
  // loaded and executed.
  $(this).show();
});

$('#ad2').loadAdScript( 'http://adnetwork.com/horrible_ad_2.js', function(){
  // This optional callback executes when the script has fully
  // loaded and executed.
  $(this).show();
});

jQuery :nth-last-child selector

Works exactly like jQuery’s built-in :nth-child selector, except that it counts from the end. Supports any index/even/odd/equation that :nth-child does.

Usage example:

// Exactly like :last-child, but slower!
var elems = $('ul li:nth-last-child(1)');

// Select every third element from the end, starting from
// the last element.
var elems = $('ul li:nth-last-child(3n+1)');

jQuery queueFn

Execute any jQuery method or arbitrary function in the animation queue. The first argument is either a function reference or the string name of a jQuery method, like “css” or “remove”. Any additional arguments will be passed into the specified method or function when it is executed. All queued functions execute, in order, in the default jQuery “fx” animation queue.

Usage example:

// Remove an element from the DOM after fading out.
$('#foo').fadeOut().queueFn( 'remove' );

// Add "fading" class to en element, but only while it's fading in.
$('#bar')
  .hide()
  .addClass( 'fading' )
  .fadeIn()
  .queueFn( 'removeClass', 'fading' );

// Change color of an element (in slightly different ways) between fades, then
// remove the element if some_condition is true.
$('a:first')
  .fadeOut()
  .queueFn( 'css', { color: 'orange' } )
  .fadeIn()
  .queueFn( 'css', 'color', 'red' )
  .fadeOut()
  .queueFn(function(){
    if ( some_condition ) {
      $(this).remove();
    }
  });

jQuery scrollbarWidth

Calculate the scrollbar width dynamically!

Usage example:

var content = $('#content').css( 'width', 'auto' ),
  container = content.parent();

if ( content.height() > container.height() ) {
  content.width( content.width() - $.scrollbarWidth() );
}

jQuery selectColorize

By default, select elements in Internet Explorer and Opera show the selected option’s color and background color, while Firefox and WebKit browsers do not. jQuery selectColorize normalizes this behavior cross-browser for basic select box color styling, without having to resort to more “fancy” select box replacements.

See this article for more information on the Firefox issue.

Usage example:

// Initialize.
$('select').selectColorize();

// Destroy.
$('select').selectColorize( false );

jQuery serializeObject

Whereas jQuery’s built-in .serializeArray() method serializes a form into an array, .serializeObject() serializes a form into an (arguably more useful) object.

Usage example:

var html = '<form>'
  + '<input type="hidden" name="a" value="1"/>'
  + '<input type="hidden" name="a" value="2"/>'
  + '<input type="hidden" name="a" value="3"/>'
  + '<input type="hidden" name="b" value="4"/>'
  + '</form>';

$(html).serializeObject(); // returns { a: [ "1", "2", "3" ], b: "4" }

jQuery viewportOffset

Like the built-in jQuery .offset() method, but calculates left and top from the element’s position relative to the viewport, not the document.

Usage example:

var elem = $('#thing');
if ( elem.viewportOffset().top > $(window).height() ) {
  // #thing element is "below the fold"
}

Post A Comment

  • Any of these HTML tags may be used for style: a, b, i, br, p, strong, em, pre, code.
  • Multi-line JavaScript code should be wrapped in <pre class="brush:js"></pre>
    (supported syntax highlighting brushes: js, css, php, plain, bash, ruby, html, xml)
  • Use &lt; instead of < and &gt; instead of > in the examples themselves.