PageRenderTime 21ms CodeModel.GetById 2ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/webapp/public/js/lib/jquery.limit.js

http://thoughtsite.googlecode.com/
JavaScript | 45 lines | 32 code | 6 blank | 7 comment | 14 complexity | 181e91088fd5f4fd7fe408bb57fcbb4d MD5 | raw file
 1(function($) {
 2    $.fn
 3            .extend( {
 4                limit : function(limit, element) {
 5
 6                    var interval, f;
 7                    var self = $(this);
 8
 9                    $(this)
10                            .keypress(function(event) {
11                                // get element
12                                    var val = $(self).val();
13                                    // Get the code of key pressed
14                                    var keyCode = event.keyCode;
15                                    // Check if it has a selected text
16                                    var hasSelection = document.selection ? document.selection
17                                            .createRange().text.length > 0
18                                            : this.selectionStart != this.selectionEnd;
19                                    // return false if can't write more
20                                    if ((val.length >= limit
21                                            && (keyCode > 50 || keyCode == 32
22                                                    || keyCode == 0 || keyCode == 13)
23                                            && !event.ctrlKey && !event.altKey && !hasSelection)) {
24                                        return false;
25                                    }
26                                });
27
28                    $(this).keyup(function(event) {
29                        // If the keypress fail and allow write more text that
30                            // required, this event will remove it
31                            substring();
32                        });
33
34                    substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
35                    if (typeof element != 'undefined')
36                        substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
37
38                    substringFunction += "}";
39
40                    eval(substringFunction);
41                    // run first time when it loads
42                    substring();
43                }
44            });
45})(jQuery);