So I borrowed code from W3Cschools (in case it looks familiar) and then started modifying it for my needs. Basically, I have a default H1 header of "Welcome to my sandbox". There's a popup that saves the user's name to a cookie. If it detects the name/cookie/variable, the H1 header changes to "Welcome (user name) to my sandbox". I can't get the (user name) to show on the first page load but it always works on the second page load. Any ideas?
Here's the code:
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1){
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1){
c_value = null;
}
else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1){
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie(){
var username=getCookie("username");
if (username!=null && username!=""){
alert("Welcome again " + username);
document.getElementById("title_script").innerHTML="Welcome "+username+" to my sandbox";
}
else{
username=prompt("Please enter your name:","");
if (username!=null && username!=""){
setCookie("username",username,365);
}
}
}
<body onload="checkCookie()" class="background_color">
<div class="wrap">
<h1 class="title" id="title_script">Welcome to my Sandbox</h1>
</div>