jQuery Plugin: BetterGrow Your Words

jquerylogo256_thumb[1]

Many things grow, but none grow better than when they BetterGrow.  Used by products such as Facebook and Basecamp, textareas that can adapt to user input, growing or shrinking their height to the demands of the text entered, provide an oft-desired minimalistic user experience of progressive enhancement – providing just what is needed by the consumer when it is needed.

facebook

Despite the widespread appeal of dynamic height textareas, I have been unable to find one such code snippet or JavaScript plugin that would meet all my needs; the most important of which was responsiveness.  Every dynamic textarea plugin that I found had some shortcoming, from delayed reaction to required grow/shrink event, to annoying visual flickers and blinks.  BetterGrow was designed to have none of these quirks, and simply grow (and shrink) better, based on the specified options and text content.

I wanted a dynamic and customizable textarea that kept up with me, that

didn’t wait until I was done typing to resize,
was much more ‘elastic’ than other similar plugins,
never obscured the entered text,
adapted both quickly and smoothly to the user.

So, I wrote the BetterGrow jQuery plugin and open-sourced it under both GPL and MIT License so that I, and everyone else, could benefit from a textarea that didn’t just grow, but grew better when it had BetterGrow. ;-)

grow_and_shrink

Usage

BetterGrow is a customizable jQuery plugin for enabling the improved, dynamic expansion of a textarea.

<div>
	<textarea id="area51">
	</textarea>
</div>
$('#area51').BetterGrow({ / * OPTIONS * / });

When the text within the target textarea exceeds the initial textarea height the textarea increases its height sufficiently to accommodate the new text.

When the text within the target textarea decreases sufficiently to allow for a lesser height, and the height is greater than the minimum textarea height or initial textarea height, then the textarea height is reduced to the minimum height required to display the text within, while not obscuring the visibility or requiring a scrollbar to view any of the text

Important:  The textarea must reside within an encapsulating DIV.  And, to avoid problems in IE, you should explicitly set the textarea’s width.

Method

When initialized, the textarea object and its parent DIV have their attributes adjusted.  The method implementation supports chaining and returns the jQuery object.

The DIV should add no size to the textarea object or region.  DIV height is automatically set to AUTO.

The textarea’s overflow is set to HIDDEN and the WIDTH is set to the current WIDTH. (FYI:  WIDTH of textarea must be defined to work in IE)

If the DIV is missing, the plugin will attempt to wrap the textarea in a new DIV.  It is recommended that all targeted textareas are wrapped in a DIV before calling BetterGrow to avoid unexpected behavior.

If the textarea already has text within it when BetterGrow is initialized, the textarea’s height is automatically adjusted to fit the text (if a height greater than the initial height is needed to present the text unobscured).

Settings

By default, the textarea’s initial empty height, aka minimum height, is set to 26px, with no special event handling enabled.  These and many other characteristics are fully customizable, and fully itemized and explained below.

To change these settings, they can either be accessed directly…

$.fn.BetterGrow.settings.initial_height = 100px;

… or at the time of initialization…

$('#area52').BetterGrow({
	initial_height:	50px,
	on_enter:		function() {
        				submit_form();
				},
	do_not_enter:	false
});

The default settings data structure is…

$.fn.BetterGrow.settings = {
	initial_height:	26,                // specified in pixels
	on_enter:		null,         // callback function; if specified, this is called when enter is pressed
	do_not_enter:	true         // if true and on_enter is not null then enter event does not cascade / pass-through to textarea
};

The parameters are defined (and all can be overridden) thus…

initial_height

  • minimum height in pixels for the textarea
  • if the textarea is EMPTY, this is the initial height

on_enter

  • callback function that is called when ENTER is pressed within the target textarea(s)
  • by default, on_enter is DISABLED (set to NULL)

do_not_enter

  • if on_enter is ENABLED (pointing to a callback function) and
    • if do_not_enter is TRUE,  then the ENTER event DOES NOT CASCADE / pass-through to the text area
    • if do_not_enter is FALSE, then the ENTER event will trigger the calling of the function referenced by on_enter and be reflected within the textarea
  • In other words, if TRUE then the content of the textarea will not change as a direct result of the user pressing ENTER.

Get It

You can download BetterGrow, dual licensed under GPL and MIT, from…

Git
Public Clone URL: git://github.com/theproductguy/BetterGrow.git
GitHub: http://github.com/theproductguy/BetterGrow

Demo

http://theproductguy.com/bettergrow/bettergrow.demo.html

If you find this useful, or have any questions, ideas, or issues, leave a comment.

Enjoy!

Jeremy Horn
The Product Guy

About these ads

jQuery Plugin: Give Your Characters a NobleCount

jquerylogo256_thumb[1] NobleCount… for a more ‘proper’ count of the characters remaining.

twitter

A very common requirement with many of the more social products of the various companies I work with is the dynamic display of the number of characters remaining in a textarea, Twitter-style. When implemented, every one of these companies either developed a simple solution in-house or found a re-usable front-end plugin online. Most common, implemented within these products, and of all I could find open-sourced online, were sources lacking customization and/or, almost universally, lacking the desired user experience – updating the character count AFTER all or most of the user’s typing had ceased.

As a result, and also in my quest to always help provide my clients free, cheap and easy to use tools, I have been on the lookout for a jQuery plugin that would provide the ability to …

  • provide non-delayed, real-time character counts,
  • enable easy to customize visual behaviors, and
  • permit event and DOM hooks for the savvy with more advanced character counting needs.

While there are other similar tools out there, none adequately met my goals. Therefore, I created the jQuery NobleCount plugin.

Usage

NobleCount is a customizable jQuery plugin for a more improved counting of the remaining characters, and handling of resulting behaviors, of a text entry object, e.g. input textfield, textarea. Also, NobleCount supports pre-existing text within the text object and jQuery chaining.

$('#textarea1').NobleCount('#characters_remaining1');
$('#textfield2').NobleCount('#characters_remaining2', { / * OPTIONS * / });

As text is entered into the target text area, an object for the purpose of tracking the total number of characters remaining, defined as the maximum number of characters minus the current total number of characters within the text entry object, is updated – storing that information visually and/or within the DOM as an HTML 5 compliant data-* attribute.

Events and CSS class alterations, if defined, are triggered based on current user interaction with the target text entry object as well as the current state (positive or negative) of the character remaining value.

Example:

$('#test1').NobleCount('#count1');
<div>
	<textarea id='test1'></textarea>
	<br>
	<span id='count1'></span> characters remaining remaining
</div>

METHOD(S)

To properly initialize, both the text entry object and the object that will store the total number of characters remaining must exist and be passed to NobleCount.

$(TEXT_ENTRY_OBJECT).NobleCount(CHARACTERS_REMAINING_OBJECT);

Both TEXT_ENTRY_OBJECT and CHARACTERS_REMAINING_OBJECT must be specified and valid.

Upon successful initialization, all appropriate events and classes are applied to the CHARACTERS_REMAINING_OBJECT, including the storage visually (if not disabled) or only in the DOM (if enabled) of the integer value representing the number of characters remaining.

The target maximum number of characters (max_chars) are determined by the following

precedence rules….

If max_chars passed via constructor
max_chars = max_chars passed
else if number exists within characters_remaining object and number > 0
max_chars = number within the text() of CHARACTERS_REMAINING_OBJECT
else use NobleCount’s default max_chars

Also note that within the NobleCount context…

NEGATIVE is defined as Integers < 0
POSITIVE is defined as Integers >= 0 [on_positive will fire when char_rem == 0]

Settings

By default, the maximum number of characters is set to 140 (à la Twitter), a negative number of characters remaining is permitted, and no events, classes, or DOM attribute modifiers are enabled.

To change these settings, they can either be accessed directly…

$.fn.NobleCount.settings.max_chars = 40;

… or at the time of initialization…

$(t_obj).NobleCount(c_obj, {max_chars:100});

The default settings data structure is…

$.fn.NobleCount.settings = {

on_negative: null,
on_positive: null,
on_update: null,
max_chars: 140,
block_negative: false,
cloak: false,
in_dom: false

};

The parameters are defined (and all can be overridden) thus…

on_negative

  • class (STRING) or FUNCTION that is applied/called when characters remaining is negative IF DEFINED
  • on_postitive class, if defined, is removed when on_negative event triggers

on_positive

  • class (STRING) or FUNCTION that is applied/called when characters remaining is positive IF DEFINED
  • on_negative class, if defined, is removed when on_positive event triggers

on_update

  • FUNCTION that is called when characters remaining changes

max_chars

  • target maximum number of characters

block_negative

  • if TRUE, then all attempts are made to block entering more than max_characters
  • if FALSE [default], text area will let individual entering the text to exceed max_chars limit (characters remaining can become negative)
  • not effective against user pasting in blocks of text that exceed the max_chars value

cloak

  • if TRUE, then no visual updates of characters remaining object (c_obj) will occur
  • if FALSE [default], then the text within c_obj is constantly updated to represent the total number of characters remaining until the max_chars limit has been reached
  • note, this does not have any effect on the char_rem value returned via any event callbacks

in_dom

  • if TRUE and cloak is ALSO TRUE, then the number of characters remaining are stored as the attribute of c_obj named ‘data-noblecount’
  • NOTE: if enabled, due to constant updating of a DOM element attribute, user experience can appear sluggish while the individual is modifying the text entry object (t_obj)

Settings example:

settings =
	{
		on_negative: 'go_red',
		on_positive: 'go_green',
		max_chars: 25,
		on_update: function(t_obj, char_area, c_settings, char_rem){
			if ((char_rem % 10) == 0) {
				char_area.css('font-weight', 'bold');
				char_area.css('font-size', '300%');
			} else {
				char_area.css('font-weight', 'normal');
				char_area.css('font-size', '100%');
			}
		}
	};

Any callback functions assigned to any of the available events are passed the following parameters: (t_obj, char_area, c_settings, char_rem)

t_obj

  • text entry object

char_area

  • characters remaining object

c_settings

  • result of the options passed into NobleCount at the time of initialization merged with the default options

Having custom function append their own data to c_settings is also a great way to pass in and remember other state information that will be needed upon the triggering of NobleCount events.

char_rem

  • integer representation of the total number of characters remaining resulting from the calculated difference between the target maximum number of characters and the current number of characters currently within t_obj

Get It

You can download NobleCount, dual licensed under GPL and MIT, from…

jQuery Repository
http://plugins.jquery.com/project/NobleCount

Git
Public Clone URL: git://github.com/theproductguy/NobleCount.git
GitHub: http://github.com/theproductguy/NobleCount

Zip
http://plugins.jquery.com/files/jQuery.NobleCount-source-bundle_1.0_20100322.zip

Demo

http://theproductguy.com/noblecount/noblecount.demo.html

Status updates can be found here, jQuery NobleCount.
If you find this useful, or have any questions, ideas, or issues, leave a comment.

Enjoy!

Jeremy Horn
The Product Guy

ThreeDots: The jQuery Ellipsis Plugin

jquery-logo-256Sometimes the text …

… is too long …
… won’t fit within the number of rows you have available.

Sometimes all you need is … ThreeDots! (a jQuery plugin)

For example —

This: When restricted to 2 lines by ThreeDots, can become:
There was once a brown fox
that liked to eat chocolate
pudding.
There was once a brown fox
that liked to eat …
There was once a brown fox
that liked to eat chocolate
pudding.
There was once a brown fox
that liked to (click for more)

… and most any other permutation you desire.

To Ellipsize

There are many scenarios in the display of online text where shortened, truncated representations are best used. For these scenarios, many products opt for the implementation of ellipses.

el·lip·sis (ĭ-lĭpsĭs)

n., pl., -ses (-sēz).

  1. The omission of a word or phrase necessary for a complete syntactical construction but not necessary for understanding.
  2. An example of such omission.
    • A mark or series of marks ( . . . or * * * , for example) used in writing or printing to indicate an omission, especially of letters or words.

[Latin ellīpsis, from Greek elleipsis, from elleipein, to fall short. See ellipse.]
from <http://www.answers.com/topic/ellipsis>

Many online products employ ellipses within their products to improve various aspects of the User Experience, such as:

allowing for easy summary scanning of page content, and
fitting more diversity of content into a smaller space.

Most often people truncate the text by character count, on both the client- and server-sides, which does not take into account the variable dimensions of the text being truncated. There are also a few CSS hacks out there, albeit with future standardized support currently being called into question, and custom, per-browser efforts required for successful implementation.

I too, on so many projects, have encountered the challenge of wanting to limit text to only a few lines or make sure that, no matter what, the text always fits within the space provided. People, myself included, on similar product feature missions have been forced to make compromises of design and experience, without the existence of a simple script/tool to carry out the task, to accommodate the time constraints and complexity of coding the ideal solution.

So, finally, I sat down, put the time in, and created the ThreeDots jQuery plugin for…

… when text is too long…
… when text doesn’t fit within the available space …
… when you want to employ highly configurable and flexible ellipses within your web product…

… so that never again, would I, or anyone else have to compromise their vision where that vision bumps up against the need for the smart implementation of ellipses in your web product.

Usage

ThreeDots is a customizable jQuery plugin for the smart truncation of text. It shortens identified text to fit specified dimensions and appends the desired ellipsis style if/when truncation occurs.

Sample 1:

<div class='text_here'>
	<span class='ellipsis_text'>
		TEXT
	</span>
</div>
$('.text_here').ThreeDots();  // USE DEFAULTS
$('.text_here2').ThreeDots({ max_rows:3 });

Sample 2:

<div class='text_here'>
	<span class='ellipsis_text'>
		TEXT
	</span>
</div>
threedots_object = $('.text_here').ThreeDots();
threedots_object.update();

Sample 3:

<div class='text here'>
	<span class='something'>
		TEXT
	</span>
</div>
threedots_object2 = $('.text_here').ThreeDots( {text_span_class: 'something'} );
threedots_object2.update( {text_span_class: 'something'} );

As a Method

When initialized, the ThreeDots plugin creates and assigns the full set of identified text to each container element, class=’text_here’, as a publicly accessible attribute, ‘threedots’. The method implementation supports chaining and returns the jQuery object.

<div class='text_here' threedots='original text'>
	<span class='ellipsis_text>
		original text
	</span>
</div>

Note, to implement the text that you wish to ellipsize, it must be wrapped in a span assigned either the default class ‘ellipsis_text’ or other custom class of your preference — customizable via the options/settings.

If the text becomes truncated to fit within the constrained space as defined by the container element that holds the ‘ellipsis_text’ span, then an additional span is appended within the container object, and after the ‘ellipsis_text’ span.

<div class='text_here' threedots='original text'>
	<span class='ellipsis_text>
		original text
	</span>
	<span class'threedots_ellipsis'>
		...
	</span>
</div>

The span class of ‘threedots_ellipsis’ can also be customized via the options/settings and have it’s own CSS/jQuery styles/actions/etc. applied to it as desired. Put another way, the ellipsis is NOT constrained to ‘…’, but can be any text or HTML you desire.

If any of the specified settings are invalid or the ‘ellipsis_text’ span is missing, ThreeDots will abort its processing and the initial text will be left untouched.

IMPORTANT: The horizontal constraints placed upon each row are controlled by the container object. The container object is the object specified in the primary selector.

$('container_object').ThreeDots();

When using ThreeDots, the following additional methods can be used…

ThreeDots.update()

Refreshes the text within the target object inline with the options provided. Note that the current implementation of options/settings are destructive. This means that whenever settings are specified, they are merged with the DEFAULT settings and applied to the current object(s), and destroy/override any previously specified options/settings.

var obj = $('.text_here').ThreeDots();	// uses DEFAULT: max_rows = 2
obj.update({max_rows:3});				// update the text with max_rows = 3

Settings

By default, the three dots ellipsis (““) is used, as shown in the prior examples, and limits text to a maximum of 2 lines. These and many other characteristics are fully customizable, and fully itemized and explained below.

To change these settings, they can either be accessed directly…

$.fn.ThreeDots.settings.max_rows = 4;

… or at the time of initialization or update …

// configuring the initial settings to use
var obj3 = $('.text_here').ThreeDots({ max_rows: 4 });

// changing the applied settings via an update call to the same text region(s)
obj3.ThreeDots.update({ max_rows: 2 });

The default settings data structure is…

$.fn.ThreeDots.settings = {
	valid_delimiters:         [' ', ',', '.'],			// what defines the bounds of a word to you?
	ellipsis_string:         '...',
	max_rows:                        2,
	text_span_class:        'ellipsis_text',
	e_span_class:                'threedots_ellipsis',
	whole_word:                        true,
	allow_dangle:                false,
	alt_text_e:                 false,					// if true, mouse over of ellipsis displays the full text
	alt_text_t:                 false					// if true & if ellipsis displayed, mouse over of text displays the full text
};

The parameters are defined (and all can be overridden) thus…

valid_delimiters

  • a character array of special characters upon which the text string may be broken up
  • defines what characters can be used to express the bounds of a word
  • all elements in this array must be 1 character in length
  • any delimiter less than or greater than 1 character will be ignored
  • if valid_delimiters contains no valid content, then nothing will be processed

ellipsis_string

  • defines what to display at the tail end of the text provided if the text becomes truncated to fit within the space defined by the container object
  • ellipsis_string can be text or HTML (e.g. ‘<a href=’url’>click for more</a>’)

max_rows

  • specifies the upper limit for the number of rows that the object’s text can use
  • if the displayed text is determined to use less than max_rows, then no operations will be performed upon the provided text and no ellipsis displayed
  • max_rows must be greater than 0 (ZERO)

text_span_class

  • by default ThreeDots will look within the specified object(s) for a span of the class ‘ellipsis_text’
  • if the class specified by text_span_class is not found within the selected objects, then no actions will be taken against the incompletely defined objects
  • if a different class name is desired for stylistic or programmatic reasons, a new, valid string can be specified

e_span_class

  • if an ellipsis_string is displayed at the tail end of the selected object’s text due to truncation of that text, then it will be displayed wrapped within a span associated with the class defined by e_span_class and immediately following the text_span_class‘ span
  • just like text_span_class, a different, valid class name can be specified

whole_word

  • when ThreeDots is fitting the provided text to the max_rows within the container object, this boolean setting defines whether or not the last word can be truncated to maximize the fit of the text within max_rows
  • if true, then don’t truncate any words and the ellipsis can ONLY be placed after the last whole word that fits within the provided space

e.g.

one time a duck flew
a frog shaped kite

…could become…

one time a duck flew
a (click for more)

  • if false, then maximize the text within the provided space, allowing the PARTIAL display of words before the ellipsis

e.g.

(continuing from the prior example)

one time a duck flew
a fr (click for more)

allow_dangle

  • a dangling ellipsis is an ellipsis that typically occurs due to words that are longer than a single row of text, resulting, upon text truncation, in the ellipsis being displayed on a row all by itself

e.g.

one time a duck flew floopydoopydoppydoodoodoodoo

… could become with allow_dangle:true …

one time a duck flew

  • if allow_dangle is set to false, whole_words is overridden ONLY in the circumstances where a dangling ellipsis occurs and the displayed text is adjusted to minimize the occurrence of such dangling of the ellipsis

e.g.

(continuing from the prior example)

one time a duck flew
floopydoopydoppyd…

alt_text_e

  • alt_text_e is a shortcut to enabling the user of the product that made use of ThreeDots to see the full text, prior to truncation, on mouse-over of the ellipsis
  • if the value is set to true, then the ellipsis span’s title property is set to the full, original text (pre-truncation) allowing the text to be seen by mousing over the ellipsis, if present
  • if the value is set to false, then the title value is left unaffected
  • this feature can be used in place of, or in conjunction with, additional styles or desired behaviors associated with mouse interactions of the selected object(s)
  • alt_text_e usage is not required to define your own custom interactions

alt_text_t

  • alt_text_t is a shortcut to enabling the user of the product that made use of ThreeDots to see the full text, prior to truncation, on mouse-over of the ellipsized text
  • if the value is set to true AND the ellipsis is displayed, then the text span’s title property is set to the full, original text (pre-truncation) and the text can be seen by mousing over the truncated text, if the ellipsis is present
  • if the value is set to false, then the title value is left unaffected
  • this feature can be used in place of, or in conjunction with, additional styles or desired behaviors associated with mouse interactions of the selected object(s)
  • alt_text_t usage is not required to define your own custom interactions

Get It

You can download ThreeDots, dual licensed under GPL and MIT, from…

jQuery Repository
http://plugins.jquery.com/project/ThreeDots

Git
Public Clone URL: git://github.com/theproductguy/ThreeDots.git
GitHub: http://github.com/theproductguy/ThreeDots

Zip
http://plugins.jquery.com/files/jQuery.ThreeDots_source-bundle_1.0.3_20091030.zip

Demo

http://theproductguy.com/threedots/threedots.demo.html

Status updates can be found here, jQuery ThreeDots.
If you find this useful, or have any questions, ideas, or issues, leave a comment.

Enjoy!

Jeremy Horn
The Product Guy

Add to Social Bookmarks: Stumbleupon Del.ico.us Furl Reddit Google Add to Mixx!