A clean way to keep your javascript out of your HTML files. Behaviors are modular units of javascript that can be associated with elements in a web page chosen with CSS selectors.
JavaScript
Switch branches/tags
Nothing to show

README.textile

jQuery Behaviors

A library of dynamic HTML behaviors, modular units of Javascript code that can be associated with elements in a web page chosen with CSS selectors.
Helps you to keep your JavaScript and HTML separated.

Browser Compatibility

  • IE 6+
  • Chrome
  • Safari 4+
  • Firefox 3.5+
  • Opera 11+

Requirements

  • jQuery 1.4+

Example

You know, doing something like the following, won’t make you any new friends:

<a onclick="window.open(this.href); return false;" href="/popup.html">open popup</a>
<a onclick="window.open(this.href); return false;" href="/another_popup.html">open another popup</a>

Instead use jquery-behaviors and you’ll end up having this clean separation:

HTML

<a data-popup="true" href="/popup.html">open popup</a>
<a data-popup="true" href="/another_popup.html">open another popup</a>

JavaScript

$.behaviors({
  "a[data-popup]:click": function(link, event) {
    window.open(link.href);
    event.preventDefault();
  }
});

Another Example

Assuming you want to fill a bunch of elements with content fetched via ajax:

<div id="ajax-content-1"></div>
<div id="ajax-content-2"></div>
<script>
  $("#ajax-content-1").load("/ajax_content.php?id=1");
  $("#ajax-content-2").load("/ajax_content.php?id=2");
</script>

With jquery-behaviors you could easily build a general ajax loading mechanism:

HTML

<output data-ajax-content="/ajax_content.php?id=1"></output>
<output data-ajax-content="/ajax_content.php?id=2"></output>

JavaScript

$.behaviors({
  "output[data-ajax-content]": function(container) {
    var $container = $(container);
    $container.load($container.data("ajax-content"));
  }
});

And Another Example

Polyfill for HTML5 autofocus:

if (!("autofocus" in document.createElement("input"))) {
  $.behaviors({
    "input[autofocus], textarea[autofocus], select[autofocus], button[autofocus]": function(element) {
      element.focus();
    }
  });
}

Contributors

Author: @tiff (based on the work of @aemkei and the idea of http://www.ccs.neu.edu/home/dherman/javascript/behavior/)