Textarea Line Count - Version 1.2


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*
  2.  *
  3.  * Textarea Line Count - version 1.2
  4.  *
  5.  * http://mosttw.wordpress.com/
  6.  *
  7.  * Licensed under MIT License: http://en.wikipedia.org/wiki/MIT_License
  8.  *
  9.  * Copyright (c) 2010 MostThingsWeb
  10.  
  11.  Permission is hereby granted, free of charge, to any person obtaining a copy
  12.  of this software and associated documentation files (the "Software"), to deal
  13.  in the Software without restriction, including without limitation the rights
  14.  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15.  copies of the Software, and to permit persons to whom the Software is
  16.  furnished to do so, subject to the following conditions:
  17.  
  18.  The above copyright notice and this permission notice shall be included in
  19.  all copies or substantial portions of the Software.
  20.  
  21.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22.  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23.  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24.  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25.  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26.  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27.  THE SOFTWARE.
  28.  */
  29.  
  30.  
  31. (function($){
  32. $.countLines = function(textarea, o){
  33. // The textarea
  34. var ta;
  35.  
  36. if (typeof textarea == "string")
  37. ta = $(textarea);
  38. else if (typeof textarea == "object")
  39. ta = textarea;
  40.  
  41. if (ta.size() != 1)
  42. return;
  43.  
  44. // Get the textarea value
  45. var value = ta.val();
  46.  
  47. var options = $.extend({
  48. recalculateCharWidth : false,
  49. chars : "",
  50. charsMode : "random",
  51. fontAttrs : ["font-family", "font-size", "text-decoration", "font-style", "font-weight"]
  52. }, o);
  53. var masterCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  54. var counter;
  55. switch (options.charsMode){
  56. case "random":
  57. // Build a random collection of characters
  58. options.chars = "";
  59. masterCharacters += ".,?!-+;:'\"";
  60. for (counter = 1; counter <= 12; counter++)
  61. options.chars += masterCharacters[(Math.floor(Math.random() * masterCharacters.length))];
  62. break;
  63. case "alpha":
  64. options.chars = masterCharacters;
  65. break;
  66. case "alpha_extended":
  67. options.chars = masterCharacters + ".,?!-+;:'\"";
  68. break;
  69. case "from_ta":
  70. // Build a random collection of characters from the textarea
  71. if (value.length < 15)
  72. options.chars = masterCharacters;
  73. else
  74. for (counter = 1; counter <= 15; counter++)
  75. options.chars += value[(Math.floor(Math.random() * value.length))];
  76. break;
  77. case "custom":
  78. // Already defined in options.chars
  79. break;
  80. }
  81.  
  82. // Decode chars
  83. if (!$.isArray(options.chars))
  84. options.chars = options.chars.split("");
  85.  
  86. // Generate a span after the textarea with a random ID
  87. var id = "";
  88. for (counter = 1; counter <= 10; counter++)
  89. id += (Math.floor(Math.random() * 10) + 1);
  90.  
  91. ta.after("<span id='s" + id + "'></span>");
  92. var span = $("#s" + id);
  93.  
  94. // Hide the span
  95. span.hide();
  96.  
  97. // Apply the font properties of the textarea to the span class
  98. $.each(options.fontAttrs, function(i, v){
  99. span.css(v, ta.css(v));
  100. });
  101.  
  102. // Get the number of lines
  103. var lines = value.split("\n");
  104. var linesLen = lines.length;
  105.  
  106. var averageWidth;
  107.  
  108. // Check if the textarea has a cached version of the average character width
  109. if (options.recalculateCharWidth || ta.data("average_char") == null) {
  110. // Get a pretty good estimation of the width of a character in the textarea. To get a better average, add more characters and symbols to this list
  111. var chars = options.chars;
  112.  
  113. var charLen = chars.length;
  114. var totalWidth = 0;
  115.  
  116. $.each(chars, function(i, v){
  117. span.text(v);
  118. totalWidth += span.width();
  119. });
  120.  
  121. // Store average width on textarea
  122. ta.data("average_char", Math.ceil(totalWidth / charLen));
  123. }
  124.  
  125. averageWidth = ta.data("average_char");
  126.  
  127. // We are done with the span, so kill it
  128. span.remove();
  129.  
  130. // Determine missing width (from padding, margins, borders, etc); this is what we will add to each line width
  131. var missingWidth = (ta.outerWidth() - ta.width()) * 2;
  132.  
  133. // Calculate the number of lines that occupy more than one line
  134. var lineWidth;
  135.  
  136. var wrappingLines = 0;
  137. var wrappingCount = 0;
  138. var blankLines = 0;
  139.  
  140. $.each(lines, function(i, v){
  141. // Calculate width of line
  142. lineWidth = ((v.length + 1) * averageWidth) + missingWidth;
  143. // Check if the line is wrapped
  144. if (lineWidth >= ta.outerWidth()){
  145. // Calculate number of times the line wraps
  146. var wrapCount = Math.floor(lineWidth / ta.outerWidth());
  147. wrappingCount += wrapCount;
  148. wrappingLines++;
  149. }
  150.  
  151. if ($.trim(value) == "")
  152. blankLines++;
  153. });
  154.  
  155. var ret = {};
  156. ret["actual"] = linesLen;
  157. ret["wrapped"] = wrappingLines;
  158. ret["wraps"] = wrappingCount;
  159. ret["visual"] = linesLen + wrappingCount;
  160. ret["blank"] = blankLines;
  161.  
  162. return ret;
  163. };
  164. })(jQuery);

URL: http://mosttw.wordpress.com/2010/09/14/textarea-line-count-jquery-plugin/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.