jQuery » Code Expander

Disable Starlight

Purpose

Take big blocks of code, and add a widget for expansion.

Code

jQuery alpha 1.0a

$("pre.sampleCode").each(function() { // find specific elements
	if ($(this).css("height") > 100) { // filter on CSS height > 100
		var _startHeight = parseInt($(this).css("height")); // store current height
		$(this).css("height", "100px")  // set height to 100px
			.wrap("<div>") // add a div to group new elements			
  		.parents("div") // Select previously added div
 				// add new child for clickable area
  			.append("<div class=\"ceexpand\">Expand Code</div>") 
  		.find("div.ceexpand") // select new child
  			.hover( // add a hover class
  				function() { $(this).toggleClass("cehover") },
  				function() { $(this).toggleClass("cehover") }
  			)
  			.toggle( // toggle the click action of the div
  				// Position Closed -> Open It
	  			function () { 
	  				// swap the class and change the HTML
	  				$(this).toggleClass("cecollapse").html("Collapse Code") 
	  					// select the pre and animate it open
	  					.siblings("pre").animate({height: _startHeight}); 
	  			},
  				// Position Open -> Close It
	  			function () { 
	  				// swap the class and change the html
	  				$(this).toggleClass("cecollapse").html("Expand Code") 
	  					// select the pre and animate it closed
	  					.siblings("pre").animate({height: 100}); 
	  			}
	  		);
	  }
  });

Styles

pre { 
	margin-bottom: 0;
	overflow: auto;
}
div.ceexpand	{
	text-align: center; 
	border: 1px solid #666; 
	border-top: 0;
	background: #efefef url(img/arrow_down.png) top right no-repeat; 
	line-height: 16px;
	width: 200px;
	margin: 0 0 0 auto;
}
div.cecollapse {
	background: #efefef url(img/arrow_up.png) top right no-repeat; 
}
div.cehover {
	background-color: #ccc;
	cursor: pointer;
}

Examples

Long Code Block

<!-- Sample HTML Indenting -->
<html>
<head>
	<title>My Page</title>
</head>

<body>
	<div>
		Some Text
	</div>
	<table>
	<thead>
		<tr>
			<th>Header 1</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Data 1</td>
		</tr>
	</tbody>
	</table>
</body>
</html>

Short Code Block

/* 
Code Highlighting 
Courtesy of Dean Edwards star-light 
http://dean.edwards.name/my/behaviors/#star-light.htc
	- with jQuery methods added, of course
*/

Icon courtesy of: http://www.famfamfam.com/lab/icons/silk/

These examples are here for your own learning. If you find yourself using part or all of them, give credit where appropriate. Enjoy!

Myles Angell
July 17th, 2006