public
Description: jQuery plugin for creating block labels
Homepage: http://bentlegen.github.com/labelize
Clone URL: git://github.com/bentlegen/labelize.git
labelize / jquery.labelize.js
100644 57 lines (46 sloc) 1.444 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* jQuery Labelize Plugin (jQuery >= 1.2.2)
*
* This work is distributed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2008, Ben Vinegar [ ben ! benlog dot org ]
*
* Usage:
*
* $('.myLabel').labelize()
*
*/
 
(function($) {
  $.fn.labelize = function(hoverClass) {
  
    function labelClickEvent() {
      // remove encompassing event (prevents jQuery recursion error in 1.3.x)
      $(this).unbind('click', labelClickEvent);
      
      // call .click on owned input
      $('input', this).click();
      
      // re-apply the event after we're done
      $(this).click(labelClickEvent);
    }
    
    var containers = $(this).filter(':has(input)');
    
    // Apply cursor attribute and onclick event to containers
    $(containers)
      .css('cursor', 'pointer')
      .click(labelClickEvent);
    
    // Apply optional hoverClass
    if (hoverClass) {
      containers
        .mouseover(function() { $(this).addClass(hoverClass) })
        .mouseout (function() { $(this).removeClass(hoverClass) });
    }
    
    // Remove encompassing label event when hovering over the
    // input element; this makes sure click() events don't fire twice
    $('input', this)
      .mouseover(function() {
        $(containers).unbind('click', labelClickEvent);
      })
      .mouseout(function() {
        $(containers).click(labelClickEvent);
    });
      
    return this;
  }
  
})(jQuery);