JavaScript notes

From Wikiid
Jump to: navigation, search

Here are some handy JavaScript widgets:

Cookies

<script language="JavaScript"><!--

function setCookie ( name, value )
{
  var exp = new Date () ;

  // 30 Day expiry time.

  exp.setTime ( exp.getTime() + 1000 * 60 * 60 * 24 * 30 ) ;

  document.cookie = name + "=" + escape ( value ) +
                    "; path=/ ; expires=" + exp.toGMTString () ;
}


function delCookie ( name )
{
  document.cookie = name + "=; path=/ ; expires=Thu, 01-Jan-70 00:00:01 GMT/";
}


function getCookie ( name )
{
  // This gets ALL of the cookies from this site - so we have to slice it out.

  var dc = document.cookie ;
  var cname = name + "=" ;

  if (dc.length > 0)
  {
    begin = dc.indexOf(cname);
    if (begin != -1)
    {
      begin += cname.length;
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
      return unescape(dc.substring(begin, end));
    }
  }

  return "" ; // Missing cookie
}

// -->
</script>

<form>
  <input type="button" value="Set Cookie"
         onClick="setCookie('myCookie','The value of my cookie!')" >
  <input type="button" value="Delete Cookie"
         onClick="delCookie('myCookie')" >
  <input type="button" value="Get Cookie"
         onClick="this.form.tf.value = getCookie('myCookie')" >
  <input type="text" name="tf" size="30" >
</form>
Personal tools