usertest usertest - 1 year ago 94
CSS Question

jquery limit text by length

Can i hide text in a DIV after a number of characters with jQuery?

So far I think it would go something like this - jQuery would cycle through the text until it gets to a certain number of characters. It would then wrap a DIV from that position to the end of the text which could then be hidden with the hide() method. I'm not sure how to insert that wrapping text.

Any other way around this would also be appreciated.


Answer Source

This will hide a part of the text

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="" xml:lang="en" lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <style type="text/css" media="screen">
    		display: none;
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
    		var $elem = $('p'); 		// The element or elements with the text to hide
    		var $limit = 10;		// The number of characters to show
    		var $str = $elem.html();	// Getting the text
    		var $strtemp = $str.substr(0,$limit);	// Get the visible part of the string
    		$str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>';	// Recompose the string with the span tag wrapped around the hidden part of it
    		$elem.html($str);		// Write the string to the DOM 

<p>Some lenghty string goes here</p>