views:

41

answers:

1

Hello,

Using the code sample below, how could I utilize the jquery cookie plugin so that the toggle state of each div element persist beyond the browser session.

Thanks.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;

        <script type="text/javascript">

        jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
        };

        $(document).ready(function(){
         $('.toggle').show();
         $('.hide').click(function(){
          var t = $(this);
          // toggle hidden div
          t.parent().find('.toggle').slideFadeToggle(400, function(){
           // determine which image to use if hidden div is hidden after the toggling is done
           var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif';
           // update image src
           t.attr('src', imgsrc );
          });
         })
        })
        </script> 

        </head>
        <body>

        <div class="wrapper">
         <img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1
         <div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
        </div>

        <p>
        <div class="wrapper">
         <img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2
         <div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
        </div>
        </p>
      </body>
    </html>
A: 

Just thinking about what you'll need, the first thing that you need to do is give each of your "wrapper" sections an ID. This ID identifies each toggleable section across page views. It does not need to be the same as the id attribute, but it would likely be easiest if the wrapper ID was the same as the id attribute value of the corresponding div.wrapper element.

Then, assuming that you want all sections to be visible initially, your cookie can store a list of IDs of sections that are hidden. This way, having no cookie means that there are no hidden sections, hence all sections are visible initially.

Each time the user hides a section, you update the cookie value to include the ID of the newly-hidden section. Each time the user unhides a section, you update the cookie value to exclude the ID of the now-visible section.

Finally, on page load, you iterate through the IDs in the cookie, hiding the sections that are listed.

Here is code to help you get started:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">

jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
};

/**
 * \returns an array of section IDs
 */
function getHiddenSectionIDs()
{
    var arr = ($.cookie('hidden_section_ids') || '').split(',');
    for (var i = 0; i < arr.length; ++i) {
        arr[i] = $.trim(arr[i]);
        if (arr[i].length <= 0)
            arr[i] = null;
    }
    return arr;
}

function setHiddenSectionIDsCookie(hiddenSectionIDs)
{
    var str = '';
    for (var i = 0; i < hiddenSectionIDs.length; ++i) {
        var id = hiddenSectionIDs[i];
        if (id !== null)
            str += ',' + id;
    }

    $.cookie('hidden_section_ids', str);
}

function toggle(t, updateCookie) {
    var t = $(t);
    var parent = t.parent();

    // toggle hidden div
    parent.find('.toggle').slideFadeToggle(400, function(){
        // determine which image to use if hidden div is hidden after the toggling is done
        var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif';
        // update image src
        t.attr('src', imgsrc );

        if (updateCookie || updateCookie === undefined) {
            var hiddenSectionIDs = getHiddenSectionIDs();
            if (parent.find('.toggle').is(':hidden'))
                hiddenSectionIDs.push(parent.attr('id'));
            else {
                for (var i = 0; i < hiddenSectionIDs.length; ++i) {
                    var id = hiddenSectionIDs[i];
                    if (id == parent.attr('id'))
                        hiddenSectionIDs[i] = null;
                }
            }

            setHiddenSectionIDsCookie(hiddenSectionIDs);
        }
    });
}

$(document).ready(function(){
    var hiddenSectionIDs = getHiddenSectionIDs();
    for (var i = 0; i < hiddenSectionIDs.length; ++i) {
        var id = hiddenSectionIDs[i];
        if (id !== null) {
            var section = $('#' + hiddenSectionIDs[i]);
            if (section) {
                toggle(section.find('.hide'), false);
            }
        }
    }

    $('.hide').click(function(){
        toggle(this);
    });
});
</script> 

</head>
<body>

<div id="section-1" class="wrapper">
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>

<p>
<div id="section-2" class="wrapper">
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>
</p>
</body>
</html>

It is far from a classy/polished solution, but I have tested it, and it works.

I used this jQuery cookie plug-in.

Daniel Trebbien
Thank you for the reply and I pretty much knew the "flow" of the process, where I am lacking is a code example to show me how it's accomplished.
Sandra
@Sandra: I was working on an example, which I have added to my answer. It demonstrates the basic idea.
Daniel Trebbien
Sorry about that and I just have one last question if I may. If a div is set to collapsed and then you refresh the page the toggle animation is kicked it which shows the div going from expanded to collapsed stated did I do something wrong or is this by design ?
Sandra
@Sandra: This is the way this code works, yes. The document ready handler uses the same `toggle` function to hide the hidden sections as the `.hide` click handler.
Daniel Trebbien
Sorry about the delay I used another method to collapse the divs and was able to get it to work as I needed. Your answer was helpful however so I thank you for that. Sandra.
Sandra