Skip to content

Instantly share code, notes, and snippets.

@jrust
Created July 19, 2011 17:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrust/1093240 to your computer and use it in GitHub Desktop.
Save jrust/1093240 to your computer and use it in GitHub Desktop.
Binding events to both onload content and ajax-loaded content.
var Application = {
// @see attach_behaviors();
behaviors: {},
init: function() {
$('body').bind('ajaxSuccess', Application.attach_behaviors);
Lessonplanet.attach_behaviors();
},
/**
* Attach all registered behaviors to a page element.
*
* Behaviors are event-triggered actions that attach to page elements, enhancing
* default non-Javascript UIs. Behaviors are registered in the Application.behaviors
* object as follows:
* @code
* Application.behaviors.behaviorName = function () {
* ...
* };
* @endcode
*
* Application.attachBehaviors is added below to the jQuery ready event and so
* runs on initial page load as well as being run whenever AJAX content is loaded
* so that behaviors are attached to loaded content as well.
*
* Behaviors should use a class in the form behaviorName-processed to ensure
* the behavior is attached only once to a given element. (Doing so enables
* the reprocessing of given elements, which may be needed on occasion despite
* the ability to limit behavior attachment to a particular element.)
*
* @credit Inspired by drupal.js
*/
attach_behaviors: function() {
$.each(Application.behaviors, function() {
this();
});
}
};
$(document).ready(Application.init);
/**
* Example behavior
* Makes labels "compact" (i.e. show up inside the form element)
*/
Application.behaviors.compact_labels = function() {
$('label.compact:not(.compact_labels-processed)').each(function() {
$(this).addClass('compact_labels-processed');
var formEl = '#' + $(this).attr('for');
if ($(formEl).val() == '') {
$(formEl).show();
$(formEl).focus(function() { $('label[for=' + $(this).attr('id') + ']').hide(); });
} else {
$(this).hide();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment