Adding Cookie to Simple script

Hey Guys,

I’ve currently got a simple script which changes some Div elements. The script is below:

<script type=“text/javascript”>

function sw() {
var d = document.getElementById(‘header’);
var i = document.getElementById(‘wrapper’);

  if ( == '200px') { = '465px'; = "url('images/bg_body_top.png')";
  } else { = '200px'; = "url('images/bg_body_to.png')";



I have a button on my website which uses an onclick event to call sw().

Everything on this script works exactly how I want it to work with one exception. I’ve been digging around trying to find out how cookies work with javascript but appear to be going round in circles.

On this page (in the 2 div’s) the default height is 465px and default image is images/bg_body_top.png, I’m wanting to setup a cookie so that if the user has clicked the button and made the height 200px and change the image to images/bg_body_to.png a Cookie is set which will last for 1 year so every time they visit the site their preference is already set.

I’m getting a little confused with the script I have developed as I’m not sure how to set a cookie for the onclick event which is cancelled when the button is clicked again to change the site back to normal.

If anyone could give any suggestions I’d be very greatful.

Thank you,

Please refer to this page on cookies where you will find good standard functions to createCookie, readCookie, and eraseCookie

Thanks for the info pmw57.

Somewhere I got very confused.

So basically what I am looking to do is create a cookie if they click once and then delete the cookie if they click a second time? Sounds in theory easy enough :smiley:

You may not want to delete the cookie, because then you are losing information. Instead, your cookie could be names something like “condensedHeader”. Then, if it’s value is read as being “yes” you can take action on that.

When they choose to expand the header with that second click, you can set condensedHeader to “no”. You may not do much with it now, but it’s there as a personal preference for some later occasion.