Monday, June 28, 2010

JQuery hide/show menu item persistence

I was working on search filters. The needed functionality is to toggle the set of checkbox elements and persist the user selected options. I want to do all this at browser end...

Here is how i did it...

Below is a html code
<div>
   <a href="javascript:void(0);" id="xyz">Click here</a>
</div>

<div id="abc">
  <div>one</div>
  <div>two</div>
  <div>three</div>
</div>

The needed functionality is when user hide/show the div with id= "abc", then it should persist untill user closes the browser..
jQuery(function(){

   // on page load call 
    <portlet:namespace/>toggleCookie("abc");
     <portlet:namespace/>hideShow("abc");

       jQuery("#xyz").click(function(){
            <portlet:namespace/>toggleCookie("abc");
            <portlet:namespace/>hideShow("abc");
        });
});


function <portlet:namespace/>hideShow(objId){
        if (jQuery.cookie(objId) == null || jQuery.cookie(objId) == "hide") {
            jQuery("#"+objId).hide();
        }
        else {
            jQuery("#"+objId).show();
        }
    }

    function <portlet:namespace/>toggleCookie(objId){
        if(jQuery.cookie(objId) == null){
            jQuery.cookie(objId, "hide");
        }
        else if(jQuery.cookie(objId) == "hide"){
            jQuery.cookie(objId, "show");
        }
        else if(jQuery.cookie(objId) == "show"){
            jQuery.cookie(objId, "hide");
        }
    }