Jump to content

show/hide divs showing by default


silvamelo

Recommended Posts

This script works fine with cookies, but I need that it shows the "Content for div" by default. I've tried to change "none" to "block", but it doesn't work... can anybody help me with it?

<html>
<head>
<script type="text/javascript">

function toggleList(id, displayValue) {
    var obj = document.getElementById(id);
    if(!displayValue)
    {
        var displayValue = 

(obj.style.display!='none')?'none':'block';
    }
    obj.style.display = displayValue;
    setCookie(id, displayValue, 30); 
    return;
}

window.onload = function()
{

accordingly
    toggleList('div1', getCookie('div1'));
    toggleList('div2', getCookie('div2'));
    toggleList('div3', getCookie('div3'));
    return;
}

function setCookie(name, value, expiredays)
{
    if (expiredays==null) { expiredays=0; }

    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate()+expiredays);

    var cookieVal  = name + '=' +escape(value) + ';expires=' 

+ expireDate.toGMTString();
    document.cookie = cookieVal; 
    return;
}

function getCookie(searchName)
{
  if (document.cookie.length>0)
  {
    var nameValuePair, cookieName, cookieValue
    var pairs = document.cookie.split(';');
    for(var i=0; i<pairs.length; i++)
    {
      nameValuePair = pairs[i].split('='); 
      cookieName    = 

nameValuePair[0].replace(/^\s+|\s+$/g,'');
      cookieValue   = 

nameValuePair[1].replace(/^\s+|\s+$/g,'');
      if(cookieName == searchName) { return cookieValue; }
    }
  }
  return false;
}

</script>
</head>

<body>

<a href onclick="toggleList('div1');">Taggle Div 1</a><br>
<div id="div1">Content for div 1</div>
<br>
<a href onclick="toggleList('div2');">Taggle Div 2</a><br>
<div id="div2">Content for div 2</div>
<br>
<a href onclick="toggleList('div3');">Taggle Div 3</a><br>
<div id="div3">Content for div 3</div>
<br>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/182106-showhide-divs-showing-by-default/
Share on other sites

Here is what i did to get what you wanted.  You had a bug which was causing page refreshes if a cookie value was set. I assumed thats not what you were wanting.  With the below changes if a cookie isnt set it default to displaying the content else it uses the cookie value.

 

Change the last line for getCookie() from

return false;

To:

return 'block';

 

Then changed your links to read.

<a href onclick="toggleList('div1'); return false;">Taggle Div 1</a>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.