Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Message Alert Help 1

Status
Not open for further replies.

26022602

Technical User
Nov 23, 2010
11
0
0
US
Hello, I am a newbie to javascript and I would like to make the code below stay on the website's homepage for as long as a viewer is on the site. I am trying to make the website as personalized as possible but I don't want the same viewer typing h/her name every time h/she goes back to the homepage. Thanks and any help is highly appreciated.


<!-- Start of Hello Visitor JavaScript-->
<!-- DESCRIPTION: This will ask the user for his/her name, then tell them WELCOME.

<!-- INSTRUCTIONS: Place this script below the BODY tag, before you start the content of your page.

<!-- FUNCTIONALITY: Works in both Netscape and IE.
-->
{
var name = prompt ('Please type in your name for personalized greeting','');
var color = prompt ('Please choose your color','');
document.write("<CENTER><FONT FACE=ARIAdL,VERDANA COLOR="+color+" >Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P>")
}
//-->
 
Hi

Store them in cookies :
Code:
[b]var[/b] name[teal]=[/teal][COLOR=darkgoldenrod]getcookie[/color][teal]([/teal][green][i]'name'[/i][/green][teal])[/teal]
[b]var[/b] color[teal]=[/teal][COLOR=darkgoldenrod]getcookie[/color][teal]([/teal][green][i]'color'[/i][/green][teal])[/teal]
[b]if[/b] [teal](![/teal]name[teal])[/teal] [teal]{[/teal]
  name [teal]=[/teal] [COLOR=darkgoldenrod]prompt[/color] [teal]([/teal][green][i]'Please type in your name for personalized greeting'[/i][/green][teal],[/teal][green][i]''[/i][/green][teal]);[/teal]
  [b]if[/b] [teal](![/teal]name[teal])[/teal] [COLOR=darkgoldenrod]setcookie[/color][teal]([/teal][green][i]'name'[/i][/green][teal],[/teal]name[teal])[/teal]
[teal]}[/teal]
[b]if[/b] [teal](![/teal]color[teal])[/teal] [teal]{[/teal]
  color [teal]=[/teal] [COLOR=darkgoldenrod]prompt[/color] [teal]([/teal][green][i]'Please choose your color'[/i][/green][teal],[/teal][green][i]''[/i][/green][teal]);[/teal]
  [b]if[/b] [teal](![/teal]color[teal])[/teal] [COLOR=darkgoldenrod]setcookie[/color][teal]([/teal][green][i]'color'[/i][/green][teal],[/teal]color[teal])[/teal]
[teal]}[/teal]
document[teal].[/teal][COLOR=darkgoldenrod]write[/color][teal]([/teal][green][i]"<CENTER><FONT FACE=ARIAdL,VERDANA COLOR="[/i][/green][teal]+[/teal]color[teal]+[/teal][green][i]" >Hello "[/i][/green][teal]+[/teal]name[teal]+[/teal][green][i]", Welcome to Willamette Family</FONT></CENTER><P>"[/i][/green][teal])[/teal]
Note that setcookie() and getcookie() are not standard functions. Search the web for suitable implementations.


Feherke.
 
HI, thanx for a quick response however nothing happens when I tried it. All I want is for the greeting to stay on the homepage for as long as a visitor is in the entire website.

MY ORIGINAL CODE:

<!-- Start of Hello Visitor JavaScript-->
<!-- DESCRIPTION: This will ask the user for his/her name, then tell them WELCOME.

<!-- INSTRUCTIONS: Place this script below the BODY tag, before you start the content of your page.

<!-- FUNCTIONALITY: Works in both Netscape and IE.
-->
{
var name = prompt ('Please type in your name for personalized greeting','');
var color = prompt ('Please choose your color','');
document.write("<CENTER><FONT FACE=ARIAL,VERDANA COLOR="+color+" >Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P>")
}
//-->
 
ps, the greetings should expire when a visitor leaves the page. I don't need to store their names for specific length of time...

thanks everyone
 
Hi

26022602 said:
MY ORIGINAL CODE:
[ul]
[li]Please do not shout, avoid all uppercase sentences.[/li]
[li]Please post your code between [tt][ignore]
Code:
[/ignore][/tt] and [tt][ignore]
[/ignore][/tt] TGML tags.[/li]
[li]You already posted that code.[/li]
[li]That is not your code, you just copied it from somewhere on the web.[/li]
[li]I wrote to get a pair of setcookie() / getcookie() functions from the web.
[ul]
[li]Have you searched for them ?[/li]
[li]Have you added them to you page ?[/li]
[li]Does the my code still do nothing ?[/li]
[/ul]
If the the answer to the 3 questions above is yes, post you modified code together with the setcookie() / getcookie() implementations you added.[/li]
[/ul]
26022602 said:
ps, the greetings should expire when a visitor leaves the page.
Hardly doable. Usually this is solved by simply setting no expire time to the cookies, so they will vanish when the browser ( the application itself, not just the given tab or the given window ) is closed.

Feherke.
 
Code:
Thanks a lot for the useful tips, I am definitely learning a lot. As I mentioned earlier, I am completely illiterate in this language and probably don't have any clue on what I have been doing. It was never my intention to claim ownership of the script I posted. My sole intention was merely to differentiate it from other posts, anticipating I'll get more responses. It was my mistake and I apologize for that. I also found myself confuse with the script lingo when I tried to understand how this thing works, and I realized that the best way for me to learn is to look at someone else's work and see how a particular tag/command (?) work. I started to do that about a week ago when I came across the script I posted and I thought it might create interest to the non-profit website I was about to launch so I decided to register on this website to ask for help. I am so sorry if I was being offensive in any way, but mostly it was my ignorance on this matter that getting in the way for me to communicate better. I have been doing some research about the cookie stuff and I will post whatever I come up with in the coming days...hopefully soon.
Again, I truly appreciate the help and tips so much...
Happy Thanksgiving!!
 
Hi

Please mark up your posts semantically : use [tt][ignore]
Code:
[/ignore][/tt] .. [tt][ignore]
[/ignore][/tt] tags only for code.

There are thousands of getcookie() / setcookie() functions all over the web, see this Google results for javascript "function getcookie" "function setcookie".

The first result, the W3Schools article JavaScript Cookies contains such functions together with explanation and usage example. As many people used to recommend W3Schools, which is dedicated to beginners, let us stay with that. So you only have to copy the two functions from the W3School page ( the content of the first two code boxes ) in front of the code I modified and posted here on 24 Nov 10 6:45.

One catch : In my code those functions are named all lowercase ( getcookie() / setcookie() ), on the W3Schools page they are camelCase ( getCookie() / setCookie() ). As JavaScript is case sensitive you have to make the function names consistent : declaration and call with identical letter case.


Feherke.
 
Hello

Thanks again, I will follow up on your tip and will post the code as soon as I have one.
 
Hi again,

I did check the tutorials on W3Schools website about cookie and no matter how I tried to understand it, it didn't make any sense to me. I copied the first two functions (from the first two boxes) and plugged in what I thought would be the necessary syntax but nothing happened when I tried it. Below is the code:

Code:
<script type="text/javascript">
function setCookie(name,color,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=name+ "=" +escape(color)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getCookie(name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + 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 "";
}

var name=getCookie('name')
{
if (!name) {
  name = prompt ('Please type in your name for personalized greeting','');
  if (!name) setcookie('name',name)
}
var color=getCookie('color')
{
if (!color) {
  color = prompt ('Please choose your color','');
  if (!color) setcookie('color',color)
}
document.write("<CENTER><FONT FACE=ARIAL,VERDANA COLOR="+color+" >Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P>")

</script>

I then tried to read other tutorials and this one somehow connects to me a little bit. Somehow, I was able to make the name and color appeared on the site but it never stayed.

Code:
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name,color) {
	var nameEQ = name + "=";
	var colorEQ = color + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var name=getCookie('name')
if (!name) {
  name = prompt ('Please type in your name for personalized greeting','');
  if (!name) setcookie('name',name)

}
var color=getCookie('color')


if (!color) {
  color = prompt ('Please choose your color','');
  if (!color) setcookie('color',color)
}
document.write("<CENTER><FONT FACE=ARIAL,VERDANA COLOR="+color+" >Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P>")

</script>

i'm sure I was doing something wrong, but I can't seem to figure exactly what...thanks again
 
[0] setcookie() is erroneous. It's case sensitive. setCookie().

[1] You name the 2nd argument color. That's quite misleading. It is meant to be the value of name. Why not just name it "value"? or something. (Overall, you have set a cookie with "name" and "color". Both are "name" in the sense of the setCookie.)
 
[2] Also, having had a look at the setCookie(), it does not look like free of problems. Any mishap to setting cookie would be of some concern, hence, I put in some more controls. A quick revision can look like this.
[tt]
function setCookie(name,color,expiredays)
{
[blue]if (name==null || name.toString().replace(/^[ ]*|[ ]*$/,'').length==0) { //do nothing in these cases
return false; //do not matter false or not
}[/blue]
var exdate=new Date();
[blue]//meaning: if you have entry 0 or a negative number, it means delete the cookie; also expiredays should be a numeric.
var d_default=1; //default to 1 day
if (expiredays==null || expiredays.toString().length == 0 || isNaN(parserFloat(expiredays)) { //non-numeric entry would mean to set cookie in this approach
exdate.setDate(exdate.getDate()+d_default);
} else {
exdate.setDate(exdate.getDate()+parseFloat(expiredays));
}[/blue]
document.cookie=name+ "=" +[blue](color==null)?"":[/blue]escape(color)+";expires="+exdate.toUTCString());
return true; //do not matter true or not
}
[/tt]
 
Thanks for the latest post, however there seem to be a problem on the red colored syntax (per Dreamweawer CS4). I tried various ways to fix it but it was to no avail. I'm not sure if it's only on this particular line or somewhere else...thanks again...
Code:
<script type="text/javascript">
function setCookie(name,value,expiredays)
{
if (name==null || name.toString().replace(/^[ ]*|[ ]*$/,'').length==0) {  //do nothing in these cases
  return false;  //do not matter false or not
var exdate=new Date();
{
if (name==null || name.toString().replace(/^[ ]*|[ ]*$/,'').length==0) {  //do nothing in these cases
  return false;  //do not matter false or not
}
var exdate=new Date();
//meaning: if you have entry 0 or a negative number, it means delete the cookie; also expiredays should be a numeric.
var d_default=1;  //default to 1 day
[COLOR=red]if (expiredays==null || expiredays.toString().length == 0 || isNaN(parserFloat(expiredays)) {  //non-numeric entry would mean to set cookie in this approach [/color]
  exdate.setDate(exdate.getDate()+d_default);
} else {
  exdate.setDate(exdate.getDate()+parseFloat(expiredays));
}
document.cookie=name+ "=" +(color==null)?"":escape(color)+";expires="+exdate.toUTCString());
return true;  //do not matter true or not
}
 
function getCookie(name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + 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 "";
}

var name=getCookie('name')
{
if (!name) {
  name = prompt ('Please type in your name for personalized greeting','');
  if (!name) setcookie('name',name)
}
var color=getCookie('color')
{
if (!color) {
  color = prompt ('Please choose your color','');
  if (!color) setcookie('color',color)
}
document.write("<CENTER><FONT FACE=ARIAL,VERDANA COLOR="+color+" >Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P>")

</script>
 
Sorry, just a typo of closing parenthese inbalance.
[tt]
if (expiredays==null || expiredays.toString().length == 0 || isNaN(parserFloat(expiredays))[highlight])[/highlight] { //non-numeric entry would mean to set cookie in this approach
[/tt]
 
Okay, I got that taken care of but still it wasn't working. Do you have any more ideas on how could I possible make this cookie stuff work? I would like to include this piece of code on the non-profit website I am working on and I think it will be an additional attraction to lure visitors in. Thanks again, and I am so sorry for being so dependent on you guys to make this happen.
 
[0] The idea flows more or less correctly but quite a few details need iron out.

[0.1] The line I'd proposed should be taken by inverse to make the shortcircuit performed as anticipated-that's one. That's my bad. (see the revision below)

[0.2] My use of ternary operation in the concatination needs a wrapping parenthesis pair. (see revision)

[0.3] And then some of your replacement of value is incomplete. It needs to happen on the function line and the content of the function as well!

[0.4] The condition
> if (!color) setcookie('color',color)
contains two errors.
[tt] if ([highlight]c[/highlight]olor) set[highlight]C[/highlight]ookie('color',color)[/tt]
and same for the case of name.

[0.5] There are a couple of {...} serving no purpose and should not be there! And I fear also the balance of curly brackets is not perfect.

[1] I take the latest post and make the revision based on it. It should at least somehow perform. (I put color argument back. If you want to change, change every place and not just the function line.)

[1.1] I wrap barely exposed line in to onload handler. I don't like the kind of style as teached(?) in w3school. I find it extremely bad taste.
[tt]
<script type="text/javascript">
function setCookie(name,color,expiredays) {
if (name==null || name.toString().replace(/^[ ]*|[ ]*$/,'').length==0) { //do nothing in these cases
return false; //does not matter false or not
}
var exdate=new Date();

//meaning: if you have entry 0 or a negative number, it means delete the cookie; also expiredays should be a numeric.
var d_default=1; //default to 1 day
//non-numeric entry would mean to set cookie in this approach
if (expiredays!=null || expiredays.toString().length != 0 || !isNaN(parserFloat(expiredays)) {
exdate.setDate(exdate.getDate()+parseFloat(expiredays));
} else {
exdate.setDate(exdate.getDate()+d_default);
}
document.cookie=name+ "=" +((color==null)?"":escape(color))+";expires="+exdate.toUTCString());
return true; //does not matter true or not
}

function getCookie(name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(name + "=");
if (c_start!=-1) {
c_start=c_start + 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 "";
}

window.onload=function() {
var name=getCookie('name')
if (!name) {
name = prompt ('Please type in your name for personalized greeting','');
if (name) setcookie('name',name)
}
var color=getCookie('color')
if (!color) {
color = prompt ('Please choose your color','');
if (color) setcookie('color',color)
}
document.write("<CENTER><FONT FACE='ARIAL,VERDANA' COLOR='"+color+"'>Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P />")
}
</script>
[/tt]
[1.2] If there are typos, I hope you should make an effort to correct it yourself. I edit these by reading line-by-line in real-time! Typo and minor errors may be inevitable.
 
amendment
[1.3] As expected, these are incompletely revised (the setcookie() have not been corrected). The block of window.onload below should be replaced.
[tt]
window.onload=function() {
var name=getCookie('name')
if (!name) {
name = prompt ('Please type in your name for personalized greeting','');
if (name) setCookie('name',name)
}
var color=getCookie('color')
if (!color) {
color = prompt ('Please choose your color','');
if (color) setCookie('color',color)
}
document.write("<CENTER><FONT FACE='ARIAL,VERDANA' COLOR='"+color+"'>Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P />")
}
[/tt]
 
amendment-2
[1.4] My reversal of the conditional has been incomplete. The or || should be replaced by && as well.

[2] To avoid misunderstanding, this is a complete relisting.
[tt]
<script type="text/javascript">
function setCookie(name,color,expiredays) {
if (name==null || name.toString().replace(/^[ ]*|[ ]*$/,'').length==0) { //do nothing in these cases
return false; //does not matter false or not
}
var exdate=new Date();

//meaning: if you have entry 0 or a negative number, it means delete the cookie; also expiredays should be a numeric.
var d_default=1; //default to 1 day
//non-numeric entry would mean to set cookie in this approach
if (expiredays!=null && expiredays.toString().length != 0 && !isNaN(parserFloat(expiredays)) {
exdate.setDate(exdate.getDate()+parseFloat(expiredays));
} else {
exdate.setDate(exdate.getDate()+d_default);
}
document.cookie=name+ "=" +((color==null)?"":escape(color))+";expires="+exdate.toUTCString());
return true; //does not matter true or not
}

function getCookie(name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(name + "=");
if (c_start!=-1) {
c_start=c_start + 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 "";
}

window.onload=function() {
var name=getCookie('name')
if (!name) {
name = prompt ('Please type in your name for personalized greeting','');
if (name) setCookie('name',name)
}
var color=getCookie('color')
if (!color) {
color = prompt ('Please choose your color','');
if (color) setCookie('color',color)
}
document.write("<CENTER><FONT FACE='ARIAL,VERDANA' COLOR='"+color+"'>Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P />")
</script>
[/tt]
 
amendment-3
[2.1] This line still contains a typo! It should be read like this. Sorry!
[tt] if (expiredays!=null && expiredays.toString().length != 0 && !isNaN(pars[highlight]eF[/highlight]loat(expiredays)) {
[/tt]
 
Whew!!! This is so much complicated than I ever thought it would be. I cannot claim I check on the script since I did not for the most part exactly what I was doing rather I PLAYED around with it. I was able to make it work, somehow, though I still have some concerns.

[1] How to make the greetings disappears as soon as the viewer leaves/close the browser

[2] I tried to add "else" statement, so the greetings doesn't show if a viewer click cancel but I don't think I did it right (as usual).

Code:
<script type="text/javascript">
function setCookie(name,value,expiredays) {
  if (name==null || name.toString().replace(/^[ ]*|[ ]*$/,'').length==0) {  //do nothing in these cases
    return false;  //does not matter false or not
  }
  var exdate=new Date();
  
  //meaning: if you have entry 0 or a negative number, it means delete the cookie; also expiredays should be a numeric.
  var d_default=[COLOR=red]0[/color];  //default to 1 day [COLOR=red] changed to "0", but still nothing happened [/color]
  //non-numeric entry would mean to set cookie in this approach 
  if (expiredays!=null && expiredays.toString().length != 0 && !isNaN(parseFloat(expiredays)) {
    exdate.setDate(exdate.getDate()+parseFloat(expiredays));
  } else {
    exdate.setDate(exdate.getDate()+d_default);
  }
  document.cookie=name+ "=" +((value==null)?"":escape(value))+";expires="+exdate.toUTCString());
  return true;  //does not matter true or not
}
 
function getCookie(name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(name + "=");
    if (c_start!=-1) {
      c_start=c_start + 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 "";
}


  var name=getCookie('name')
  if (!name) {
    name = prompt ('Please type in your name for personalized greeting','');
    if (name) setCookie('name',name)
  }
[COLOR=red]{
else if (!name) return ="false";
}[/color]
  var color=getCookie('color')
  if (!color) {
    color = prompt ('Please choose your color','');
    if (color) setCookie('color',color)
  }
  document.write("<CENTER><FONT FACE='ARIAL,VERDANA' COLOR='"+color+"'>Hello "+name+", Welcome to Willamette Family</FONT></CENTER><P />")
</script>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top