Hyphenating Strings with jQuery
Over the course of the past couple weeks, my need for a method of string hyphenating DOM objects has arisen quite often. Any UI developer that has to deal with user input with limited space will know that this can be a big pain. Like a true software engineer, I searched the interwebs to see if there were any existing plugins to handle this for me. Shockingly, I found no viable solutions, so I wrote my own jQuery Plugin to handle the hyphenating.
Jump to the jQuery Hyphenate Demo
Download the Source Code
Requirements
In the head of your document, be sure to include your references to the jQuery library and the Hyphenate Plugin:
<script type="text/javascript" src="js/jquery-1.3.2.js"></script> <script type="text/javascript" src="js/jquery.hyphenate.js"></script>
Following that, we can instantiate our plugin on any dom element:
jQuery(document).ready(function(){ // Document is ready $('div.hyphen').hyphenate(); // Hyphenate all divs with a class of 'hyphen' });
By default, the plugin will hyphenate the strings based off the current width of the element we are hyphenating. You can, however, pass in an optional oWidth parameter to define a width for the element.
jQuery(document).ready(function(){ // Document is ready $('div.hyphen').hyphenate({ oWidth : 100 }); // Hyphenate all divs with a class of 'hyphen' to a width of 100px });
This plugin works best with block level elements (DIV, P, H1, LI), but can also work on inline elements (SPAN, EM, STRONG), just note that the plugin will modify them to block level via display:block.
Known Issues
This plugin is in its initial release, so please do not consider this a complete and polished plugin.
- Nested DOM elements will be removed. If you are performing a hyphenation on a DIV that has child SPANs or As, then those elements will be removed, though there inner-text will remain.
Please enjoy! Feel free to leave comments and suggestions below, and don’t forget to come back often to check for updates.
1 Comment
Jump to comment form | comments rss [?] | trackback uri [?]