views:

689

answers:

2

I have a cookie that I did using javascript and to check if it had to be replaced I used "onload=checkCookie()" in the body tag of the HTML, however now I'm trying to place the js in another file and just link it using the tag, but if I do that I can no longer call this function using just "onload" so I was wondering how can I do this? everybody else I've asked tells me to leave the code there, but I want to separate my design in layers =S

here's the js:

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 "";
}

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.toGMTString());
}

function checkCookie(){
    username=getCookie('username');
    if(username!=null && username!=""){
     alert('Welcome again '+username+'!');
    }else{
     username=prompt('Please enter your name:',"");
     if(username!=null && username!=""){
      setCookie('username',username,365);
     }
    }
}

Everything is inside a file called init.js

+2  A: 

I don't understand the issue, you should be able to use the body's onload to execute javascript even if it is from an external file, like this:

This is the html:

<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="hello()">
</body>
</html>

This is the linked javascript:

var hello = function()
{
    alert("Hello!");
}
Daniel Lew
+1  A: 

Getting the script in a separate file is a good thing. Add the onload function to the script-

window.onload=checkCookie; //(no parenthesis) and take it out of the html.

kennebec
Thanks! just what I needed
Luis Armando