None

Storing data on the DOM using jQuery

January 6, 2010

On this blog, I have a maximise link at the top right of this post. This maximises the main body of the post, removing the right hand sidebar in the process. (This lets you see the long lines of code I sometimes put in here.) Clicking again minimises. This is done using jQuery.

Problem

IE6 doesn't display the right hand menu correctly - it pushes it below all of the content, and there's a big blank space down the right hand side. To sort this out, I'm now delivering specific CSS for IE using a conditional comment:

<link rel="stylesheet" type="text/css" href="/site_media/iphone.css" 
                       media="screen and (max-device-width: 480px)" />
<link rel="stylesheet" type="text/css" href="/site_media/style.css" 
                       media="screen and (min-device-width: 481px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="/site_media/ie.css" media="screen" />
<![endif]-->

This IE specific CSS has different widths for the sidebar and main content divs.

I was previously using hard coded widths in the CSS to restore width on minimise; this obviously doesn't work if the values are different on different style sheets.

Solution

Here's the new Javascript. It uses jQuery to store the width on the DOM when maximising, then restores this value when minimising again.

$('#max').click(function(){
    if ($('#max').data('minmax') === 'max'){
      var lWidth = $('#content').data('min-width');
      $('#content').css('width', lWidth);
      $('#sidebar').show('slow', function(){
        $('#max').text('>').attr('title','Maximize').data('minmax','min');
      });   
    } else {
      $('#sidebar').hide('slow', function(){
        var lWidth = $('#content').css('width'); 
        $('#content').data('min-width', lWidth);
        $('#content').css('width', '900px');
        $('#max').text('<').attr('title','Minimize').data('minmax', 'max');
      });
    }
});

Tags: jquery dom data css