How to create a jquery code-snippet box

GFX9.COM share How to create a jquery code-snippet box, you can download now.



In this tutorial we're going to be creating a code-snippet box that displays example code on web pages in an attractively formatted and easy to read way, much like what you see here on Nettuts. Code-snippet preview boxes like this are often made as Wordpress plugins, but we'll see how we can do the same thing with just a little jQuery and CSS.

We can add all of the expected features such as line-numbering and line striping, and all of the usual tools such as viewing the code as plain text and printing it in a printer-friendly manner. The following screenshot shows the kind of thing that we'll end up with by the end of the tutorial:



Getting Started

The code-snippet box will be built from an underlying

 element; this is the perfect element to use because it renders whatever you put into it as plain text in a fixed-width font such as monospace, which is ideal for showing code samples in a clear and concise manner. It also preserves line-breaks which is a feature we can exploit in order to add the line numbering and striping features.

Another reason we use the

 tag is because it makes the ideal foundation for our code box; in browsers with JavaScript disabled, or those that simply don't support it, the code will still be rendered acceptably. It'll stand out from the rest of the text on the page and it won't degenerate into something completely useless and ridiculous.

Start off with the following page in your text editor:

 
 
   
     
    jQuery Code-snippet Box 
     
   
   
    

CSS Code:

#selector { color:#000000; } 
.another-selector { font-size:20px; border:1px solid #000000; padding:20px; } 
tagname { width:100%; }

Save the page as code-snippet.html in a directory that already has the current version of jQuery residing within it. With no styling and no script intervention the page should look like this:


As a default fall-back it's acceptable; if the page had other body text on it, the

 element would stand out as a separate block of text and would still appear a little code-like.


Beginning the scripting

Let's make a start by adding the striping effect that will make each line stand out from those above and below it, and the line numbering which will show when a broken line (which overflows on to two or more lines) is part of one line of example code.

In the empty


Similar content