usertest usertest - 2 months ago 17
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.

Thanks.

Answer

This will hide a part of the text

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>untitled</title>
    <style type="text/css" media="screen">
    	.hide{
    		display: none;
    	}
    </style>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
    	$(function(){
    		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 
    	})
    </script>

</head>
<body>
<p>Some lenghty string goes here</p>
</body>
</html>
Comments