Displaying Code Snippets on a Webpage

Recently we were crafting a web page for use in one of our Training classes – we needed a simple, clean display of code snippets that users could easily copy/paste from. Our initial inclination was the classic approach of wrapping the snippets in <pre> and/or <code> tags, but this left plenty to be desired, not least of which was the loss of line-breaks when using the <pre> tag and spacing/indentions with the <code> tag.

Our eventual solution instead took the idea of using a <textarea>, which maintained the formatting we wanted, and simply styling it with CSS to create a more transparent effect. So this: BeforeCSS

…became this:

AfterCSS

Using this CSS:

textarea.CodeBox {
width:100%;
border:none;
background-color:transparent;
resize:none;
outline:none;
overflow:hidden;
padding:0
}

In our case though, we had the added “gotcha” that browsers assume a relatively small box size for textareas; and worse, there’s no pure CSS method for setting the height of a <textarea> to just tall enough to display all the text therein. And even if you decide you’re not opposed to fixing a static height for each box, if you’re specifying the width as a percentage (100% in our case), your static heights won’t work if/when the user resizes their browser window.

So to account for that added behavior, we dropped in a little jQuery logic. Using a “setTimeout” function inside an event handler bound to window resizing, we can resize the height of all our <textarea> elements to be just the right size:

var ResizeDone;
$(window).resize(function() {
clearTimeout(ResizeDone);
ResizeDone = setTimeout(RightSizeBoxes, 100);
});function RightSizeBoxes() {
$(‘textarea.CodeBox’).each(function() {
$(this).height($(this)[0].scrollHeight);
});
}

The reason for the “setTimeout” is because the resize event will fire for every change of the window size, in either direction, by even one pixel. We didn’t want to flood the DOM, or risk locking the browser, so by incorporating a “setTimeout” – in our case, for 100ms but you can use any value you want – we’re ensuring the user has stopped resizing the window for at least 100ms before fixing the <textarea> heights. Fast enough that the user doesn’t notice, but written so the resize event doesn’t fire potentially hundreds of times as the user changes their browser window size.

Comments are closed.