jQuery Code Expander

11 January 2010 Monday

This application was viewed 731 times




jQuery Code Expander

There is a problem on the web. Displaying actual programming code takes away a lot of space of the webpage (especially the longer ones). You can split up the code in several parts, but that´s really hard to read for programmers. You can leave it "as it is" and users would have to scroll a lot if they´re not interested in the code itself. And scrollbars in code-examples - that´s just horrible (and yes - that´s what I have on this website).

View the DEMO

I created a solution for this problem and call it the jQuery Code Expander. It does exactly what you think it does - Expand any code you want to place online using jQuery.

But, before you can expand anything, it has to be cropped. That´s where the CSS kicks in. It´s like a combination of using scrollbars and fully showing the code!

This script only changes those elements that needs to be expanded and doesn´t touch those who don´t. An additional overlay image is added, just to show the user that it can expand the code example. Check out the demo and read below what the secret of this technique is.

HTML

Although the HTML is very simply, it´s vital to make this technique work. It looks like this:

 
<pre class="jcexpander"><code>
   <!-- Your code goes here -->
</code></pre>

The pre-element has a class (jcexpander) and one child element (code). That´s all we need!

CSS

Once again, the CSS is really small, but this is another key to let this technique be a success. I´ve only placed the important stuff here - you can view the full CSS in the download.

 
pre.jcexpander {
   width:80%;
   height:500px;
   overflow:hidden;
}

As you can see, the pre element has been trimmed down. The overflow is set to hidden so you won´t see the scrollbars. You should have a cropped version of the code block right now. Now, on to the jQuery part!

jQuery

There is something really important going on over here: Although the pre-element has been cropped down, the code-element hasn´t. This means, that when you request the size of the code-element, you would get the size of how big it really is (when it wasn´t cropped). That information is what we´re going to use next.

 

I came up with the following script (which also adds the icon on top). Comments are added to make things clear.

 
/*
* Author:      Marco Kuiper (http://www.marcofolio.net/)
*/
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function()
{
   // We´ll need to loop through each <pre> element
   // with the class "jcexpander"
   $("pre.jcexpander").each(function(){
      
      // Only do something when the inner element (the <code> element)
      // is bigger than the parent (<pre>) element
      if( $("code", this).height() > $(this).height() ||
         $("code", this).width() > $(this).width()) {
         
         // We´ll need to store the original values of the sizes
         // since we´ll use it to "grow back"
         $(this).data(´originalHeight´ , $(this).height());
         $(this).data(´originalWidth´, $(this).width());
         
         // Create a IMG element for the overlay
         var icon = document.createElement("img");
         $(icon).css({ ´position´ : ´absolute´});
         $(icon).attr("src", "images/fullscreen.png");
         
         // Append the image to the <pre> element
         $(icon).prependTo($(this));
         
         // When the <pre> element is hovered, this happens
         // First function is "over", second is "out"
         $(this).hover(function(){
            // Fade out the image
            $(icon).fadeOut();
            
            // Read the size of the <code> element
            var codeWidth = $("code", this).width();
            var codeHeight = $("code", this).height();
            
            // Size the <pre> element to be just as big
            // as the <code> element
            $(this)
               .stop()
               .animate({
                  width : codeWidth + "px",
                  height : codeHeight + "px"
               }, 1500);
               
         }, function(){
            // Fade in the image
            $(icon).fadeIn();
            
            // Size the <pre> element back to the
            // original size.
            $(this)
               .stop()
               .animate({
                  width : $(this).data(´originalWidth´) + "px",
                  height : $(this).data(´originalHeight´) + "px"
               }, 1500);
         });
      }
   });
})

Tags: expand, jquery, code,


jQuery Code ExpanderBookmark and Share

You write your thoughts

Please login to post comments here from the right corner.

your add
icon free icon icon set vector icon free catalog catalog template jquery news ticker widget tools tutorial php slider video youtube effects menu thumbnail forms facebook zoom image combo multiselect modal polaroid gallery expand code feedback contact navigation slider tagcloud Skateboard psd templates files badges subscribe panel login temlate file free office holland free template tabs prototype css scriptaculous opacity moo autocomplete wordpress themes design theme button images photoshop fonts font nav pdf logo style high javascript pretty photo jqery lightbox Themes Blog popular blog desing joomla xhtml brushes hair footer admin mootols slide show blackbox new download class first plugin upload browse Page effect modalbox web application urlitooltips sliding boxes captions flatchat chat ajax messaging browser hoverlightbox CSS Dev General Javascript PHP SQL search avatar vector Drupal Joomla Oscommerce javaScript phototype manager ajaxplorer flash xml rotator bookmarking pageflip slideshow poll text component script mediaplayer imagegallery pictograms car poster player mp3 radio onlineradio navigations drop-down collection brush tree textures paper pop-up bumpbox web2.0 iphone film frame twitter page fan mail delete dynamic calender form handbook city social paint timeline clock connect bar sharing accordion quotes ticker photo-effects background 3D media player graphic rss leaf green glossy bubble icon comic clean cool web 2.0 png actionscript ietter rotating Menu animated textured site masking pasword app layer sponge bob popup bubble tooltips horizontal prototip tooltip pack charachters comics blog action icon.psd flavour navi tango gradients istanbul mixed css3 sleek animations program html5 website Layer styles ultimate candy Media icons dropdown snow icon innerfade hover sub tag