Help on implementing Cookies to a simple script in JavaScript

Discussion in 'JavaScript' started by veo6, Dec 21, 2010.

  1. #1
    This code opens and closes a 'container' div by changing the css style to display:block; and display:hidden;

    I need to implement cookies to it so that when it closes and the page is refreshed, it remains CLOSED or OPEN.

    Here is the Javascript:

    Here is the HTML:


    ALL SOURCE is on this link: http://www.brenz.net/snippets/open_close_div.asp


    Please help! I'm novice in JavaScript.

    Your help is very much appreciated :D
     
    veo6, Dec 21, 2010 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    
    <script type="text/javascript">
    var myChecker;
    
    function lunchboxOpen(lunchID) {
    	document.getElementById('lunch_' + lunchID).style.display = "block";
    	document.getElementById('clasp_' + lunchID).innerHTML="<a href=\"javascript:lunchboxClose('" + lunchID + "');\">Close Lunchbox " + lunchID + "...</a>";
    	setCookie('lunch_'+lunchID','block',36500);
    }
    function lunchboxClose(lunchID) {
    	document.getElementById('lunch_' + lunchID).style.display = "none";
    	document.getElementById('clasp_' + lunchID).innerHTML="<a href=\"javascript:lunchboxOpen('" + lunchID + "');\">Open Lunchbox " + lunchID + "...</a>";
    	setCookie('lunch_'+lunchID','none',36500);
    } 
    
    
    function setCookie(c_name,value,expiredays)
    {
    	var exdate=new Date();
    	exdate.setDate(exdate.getDate()+expiredays);
    	document.cookie=c_name+ "=" +escape(value)+
    	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
    }
    
    function getCookie(c_name)
    {
    	if (document.cookie.length>0)
    	{
    		c_start=document.cookie.indexOf(c_name + "=");
    		if (c_start!=-1)
    		{
    			c_start=c_start + c_name.length+1;
    			c_end=document.cookie.indexOf(";",c_start);
    			if (c_end==-1) c_end=document.cookie.length;
    				return unescape(document.cookie.substring(c_start,c_end));
    		}
    	}
    	return "";
    }
    
    myChecker = setTimeout ( "checkReady()", 100 );
    
    function checkReady()
    {
    	var body = document.getElementsByTagName('BODY')[0];
    	if(body && body.readyState == 'loaded')
    	{		
    		clearInterval(myChecker);
    		checkCookies();
    	}
    }
    
    function checkCookies()
    {	
    	var cookie1 = getCookie('lunch_1');
    	if(cookie1 != 'block'){ lunchboxOpen(1);}
    	var cookie2 = getCookie('lunch_2');
    	if(cookie2 != 'block'){ lunchboxOpen(2);}	
    }
    </script>
    
    PHP:
    If you are using Jquery, it would've made it more easier.
     
    ThePHPMaster, Dec 21, 2010 IP