Example Drupal Behavior

Last modified: 
Friday, August 28th, 2015

This is an example of a Drupal behavior. Drupal behaviors ensure scripts run on elements updated via AJAX.

I'm not sure about the closing bit. I inherited it from a live system.

(function ($, Drupal, window, document, undefined) {
  /**
   * Seeks out picture elements with the class "has-caption" and uses 
   * the title to create a caption.
   * @type {{attach: Function}}
   */
  Drupal.behaviors.hasCaptions = {
    attach: function (context, settings) {
      $('picture.has-caption').each(function() {
        var title = $('img', $(this)).attr('title');
        if (title) {
          $(this).wrap('<span class="caption-wrapper"></span>')
                 .append('<span class="caption">'+title+'</caption>');
        }
      });
    }
  };

})(jQuery, Drupal,window, document);


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.