...

View Full Version : Need help with background cookie function..



ShadowIce
05-18-2009, 09:25 PM
Hi all :) I've been researching cookies a bit, and I attempted to create a function that if you select a background name from a drop down list or anything for that matter, it will save the background in the cookie, and display it in a div background for later use. Now I can't quite figure out why there is a problem with this script, but the error checker tells me there is.

Heres the code:


<script type="text/javascript">

//Get Cookie

function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
// if cookie exists
if (offset != -1) {
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset);
// set index of end of cookie value
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function setbg(what){
document.getElementById("mydiv").style.backgroundimage=url(what);
document.cookie="backgroundimage="+what
}

if (get_cookie("bg")!="")
document.getElementById("mydiv").style.backgroundimage=get_cookie("bg")

</script>

<form name="a1">
<p><select name="a2" size="1">
<option selected value="NA">Select background</option>
<option value="myimage.gif">My Image</option>
</select>
<div id="mydiv"></div><a href="javascript:setbg(document.a1.a2.options[document.a1.a2.selectedIndex].value)">Set Bg</a></p>
</form>

ANY help is GREATLY appreciated! :)

Thanks! :)

~SI~

Old Pedant
05-19-2009, 03:25 AM
Would have found this quickly if you'd used a debugger.



document.getElementById("mydiv").style.backgroundimage=url(what);


Nope.

Now try:


document.getElementById("mydiv").style.backgroundImage=url(what);


backgroundimage is *NOT* the same as backgroundImage. JavaScript is case sensitive, remember?

But several other mistakes.

You set the cookie using the name backgroundimage but then try to retrieve a cookie name bg. Make up your mind.

And where is that function url( ) defined??? Not any place on this page.

Oh..and you can't set the background color of a <div> that isn't yet even loaded into the browser! You'll need to do the get_cookie call via <body onload=> or equivalent.

ShadowIce
05-19-2009, 02:51 PM
Ok. I fixed what I could. But it still returns an invalid argument.


<body onload="get_cookie('backgroundImage');">
<script type="text/javascript">

//Get Cookie

function url(what){

alert(what);

return what;

}

function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
// if cookie exists
if (offset != -1) {
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset);
// set index of end of cookie value
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function setbg(what){
document.getElementById("mydiv").style.backgroundImage=url(what);
document.cookie="backgroundImage="+what
}

if (get_cookie("backgroundImage")!="")
document.getElementById("mydiv").style.backgroundImage=get_cookie("backgroundImage")

</script>

<form name="a1">
<p><select name="a2" size="1">
<option selected value="NA">Select background</option>
<option value="myimage.gif">My Image</option>
</select>
<div id="mydiv"></div><a href="javascript:setbg(document.a1.a2.options[document.a1.a2.selectedIndex].value)">Set Bg</a></p>
</form>

Any ideas?

ShadowIce
05-19-2009, 07:02 PM
Ok. this works. i redid the data functions. the only prob is, when i leave and come back to the same page, or refresh, it doesnt save the background.. even though the cookie is correct, as u can use alert(GetCookie('image')); to see.

Here's the code:


<body background="GetCookie('image');">
<script>
var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function image(){
var favImage = GetCookie('image');
if (favImage == null) {
favImage="mypic.gif";
SetCookie('image', favImage, exp);
}
alert(GetCookie('image'));
document.body.background=favImage;
return favImage;
}
function set(){
favImage="mypic.gif";
SetCookie ('image', favImage, exp);
}
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
alert();
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
</script>
<input type="button" name="bg" value="Change Background" onClick=image();>

Thanks! :)

~SI~

Old Pedant
05-19-2009, 09:42 PM
This line is illegal:


<body background="GetCookie('image');">

You can't call a function from a property. Only from an *event*.

Try this:


<body onload="image();">

ShadowIce
05-19-2009, 10:26 PM
Ok. I fixed it. the only prob now is when i click the change background button, it changes the background, but when i refresh, it reverts back to the default background. when u click the button, i need it to stay on the chosen background. the default background is here: '<div id="mydiv" style="background-image: url('default.jpg'); width: 400; height: 300;"></div>'

here's the code:


<!--<body onload="image();">-->

<script>

var expDays = 365;
var exp = new Date();
var favImage = "";

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

function image(){

var favImage = GetCookie('image');

if (favImage == null) {

favImage="./mypic.gif";
SetCookie('image', favImage, exp);

}

document.getElementById('mydiv').style.backgroundImage='url('+favImage+')';

return favImage;

}

function set(){

favImage = "./mypic.gif";
SetCookie ('image', favImage, exp);

}

function getCookieVal (offset) {

var endstr = document.cookie.indexOf (";", offset);

if (endstr == -1)
endstr = document.cookie.length;

return unescape(document.cookie.substring(offset, endstr));

}

function GetCookie (name) {

var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;

while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}

return null;

}

function SetCookie (name, value) {

var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;

document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");

}

function DeleteCookie (name) {

var exp = new Date();

exp.setTime (exp.getTime() - 1);

var cval = GetCookie (name);

document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();

}

</script>

<div id="mydiv" style="background-image: url('default.jpg'); width: 400; height: 300;"></div>
<input type="button" name="bg" value="Change Background" onClick=image();>

ANY help is GREATLY appreciated! :)

~SI~

Old Pedant
05-20-2009, 01:21 AM
A lot of that makes no sense. And you don't show the <select> which I *assume* is where you are getting the possible image names from.

The GetCookie code strikes me as cumbersome.

I don't *have* a bunch of background images to test against, so I just used colors. Here:


<script>
var expDays = 365;
var exp = new Date();
var favImage = "";
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function saveImage(form)
{
var favImage = form.favSelect.value;
SetCookie('image', favImage, exp);
document.body.style.backgroundColor = favImage;
}

function GetCookie(name)
{
var cookies = document.cookie.split(/; /g);
var arg = name + "=";
for ( var c = 0; c < cookies.length; ++c )
{
var ck = cookies[c];
if ( ck.indexOf(arg) == 0 )
{
var temp = ck.split(/=/);
return unescape(temp[1]);
}
}
return "";
}

function SetCookie (name, value)
{
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;

document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}

function DeleteCookie (name)
{
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
</script>

<body onload="document.body.style.backgroundColor=GetCookie('image');">
<div id="mydiv" style="background-color: white; width: 400; height: 300;">
fun stuff
<form>
<select name="favSelect" onchange="document.getElementById('mydiv').style.backgroundColor=this.value;">
<option value="white" style="background-color: white;">white</option>
<option value="yellow" style="background-color: yellow;">yellow</option>
<option value="lightgreen" style="background-color: lightgreen;">light green</option>
<option value="lightblue" style="background-color: lightblue;">light blue</option>
<option value="wheat" style="background-color: wheat;">wheat</option>
<option value="pink" style="background-color: pink;">pink</option>
</select>
<input type="button" name="bg" value="Change Background" onClick="saveImage(this.form);">
</form>
</div>


I think that if you just changed to using image URLs in place of the colors in the option values, and if you changed all use of "style.backgroundColor" to "style.backgroundImage" then this should work.

When you change the <SELECT>, it automatically previews the color (or image) as the background of that <DIV>. Then, when you click the button, it gives that color (or image) as the background to the entire <BODY>.

Is this something like what you were after?

It doesn't matter if the <form> is inside or outside of the sample <div>.

ShadowIce
05-20-2009, 02:17 AM
Thanks :) And almost. But the only prob is it wont use the image value the cookie stores to read it, so its that picture everytime, no matter if u use onload or not.

when u click the button, it applies the image to the div, and saves it, so it will display in that same div after going to another page, and coming back to my page. just download any pic from online or draw it using paint, and name it mypic.gif and default.jpg.

I edited the code so it works with images, but still it will not save when u leave & come back, using the cookie's image value as the image link.


<script>
var expDays = 365;
var exp = new Date();
var favImage = "";
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function saveImage(form)
{
var favImage = form.favSelect.value;
SetCookie('image', favImage, exp);
alert(favImage);
document.body.style.backgroundImage='url('+favImage+')';
}

function GetCookie(name)
{
var cookies = document.cookie.split(/; /g);
var arg = name + "=";
for ( var c = 0; c < cookies.length; ++c )
{
var ck = cookies[c];
if ( ck.indexOf(arg) == 0 )
{
var temp = ck.split(/=/);
return unescape(temp[1]);
}
}
return "";
}

function SetCookie (name, value)
{
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;

document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}

function DeleteCookie (name)
{
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
</script>

<body onload="document.body.style.backgroundImage='url(\'GetCookie(\"image\");\')';">
<div id="mydiv" style="background-image: url('default.jpg'); width: 400; height: 300;">
fun stuff
<form>
<select name="favSelect" onchange="document.getElementById('mydiv').style.backgroundImage=this.value;">
<option value="mypic.gif">MyBackgroundPic</option>
</select>
<input type="button" name="bg" value="Change Background" onClick="saveImage(this.form);">
</form>
</div>

ANY help is GREATLY appreciated :)

~SI~

Old Pedant
05-20-2009, 02:33 AM
No, you STILL have bad JS in there.

Try something like this:


<body onload="document.body.style.backgroundImage='url(\'' + GetCookie('image') + '\')';">


Don't you turn on your JavaScript DEBUGGER when trying to write JS code????

That code you used gives any browser hairy fits.

Okay, I give up. I'll go try this on my own page with images.

Old Pedant
05-20-2009, 02:47 AM
Here, a working demo, with images:

http://www.clearviewarts.com/cookiebgi.html

ShadowIce
05-20-2009, 03:10 AM
Dude! Its PERFECT! Thank you SO much for all your help! :)

ShadowIce
05-20-2009, 05:26 PM
Ok. I have 1 more small question. Then this is complete :)

How do I use an array and an if function to tell thefinal variable which picture to display depending on what is selected, and save the selected image value to the cookie using saveImage() ?

heres the code:


<script>
var thediv = "mydiv";

var thedefault = "default.jpg";

var theimg = "myimg.gif";

var num = 0;

var thefinal = [];

thefinal[0] = thedefault;
thefinal[1] = theimg;

var thecolor = "blue";

function menu(){

num++;

document.write('<form name="theform">\n'

+'<select name="favSelect" onchange="getDivBG(thediv, thefinal`);">\n'
+' <option selected="true" value="">--choose--</option>\n'
+' <option value='+thefinal[num]+'>Default</option>\n'
+' <option value='+thefinal[num]+'>My Image</option>\n'
+' </select>\n'
+'</form>\n');

for(var x=1;x<=document.forms.theform.favSelect.length;x++){

if(document.forms.theform.favSelect.selected != ""){

saveImage(thediv, thefinal[x]);

}

}

if(document.forms.theform.favSelect.selected){

alert(thefinal[num]);

}

}

var expDays = 365;
var exp = new Date();
var favImage = "";
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function saveImage(thediv, pic)
{
var favImage = pic;
if ( favImage == "" ) return;
SetCookie('image', favImage, exp);
getDivBG(favImage);
}

function savetheColor(thediv, thecolor)
{
var favColor = color;
SetCookie('image', favColor, exp);
document.body.style.backgroundColor = favColor;
}

function GetCookie(thename)
{
var cookies = document.cookie.split(/; /g);
var arg = thename + "=";
for ( var c = 0; c < cookies.length; ++c )
{
var ck = cookies[c];
if ( ck.indexOf(arg) == 0 )
{
var temp = ck.split(/=/);
return unescape(temp[1]);
}
}
return "";
}

function SetCookie (thename, thevalue)
{
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;

document.cookie = thename + "=" + escape (thevalue) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}

function DeleteCookie (thename)
{
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (thename);
document.cookie = thename + "=" + cval + "; expires=" + exp.toGMTString();
}

function getBodyBGColor()
{
document.body.style.bgColor="url('" + GetCookie("color") + "')";
}

function getBodyBG()
{
document.body.style.backgroundImage="url('" + GetCookie("image") + "')";
}

function getDivBGColor(thediv, thecolor)
{
if ( thecolor != "")
document.getElementById(thediv).style.bgColor="url('" + thecolor + "')";
}

function getDivBG(thediv, pic)
{
if ( pic != "")
document.getElementById(thediv).style.backgroundImage="url('" + pic + "')";
if(document.forms.theform.favSelect.value != "") alert(document.forms.theform.favSelect.value);
document.getElementById(thediv).style.backgroundPosition="Center";
}
</script>
<body onload="getDivBG(thediv, theimg);">
<form name="theform">
<div id = "mydiv" style="width: 400; height: 250;">My Div</div><script>menu();</script>
</form></body>

Thanks again for all your support! :)

~SI~

ShadowIce
05-20-2009, 11:11 PM
Sorry if I'm overwhelming you. you dont have to answer if you dont want to. I'll just ask on another forum :) Thats fine :)

But know this. I really appreciate what you have already done for me, and appreciate anyhthing else you will do if you choose to answer :)

Thanks again! :)

~SI~

ShadowIce
05-21-2009, 08:32 PM
Can someone please help? This is the last question I have about cookies....

Old Pedant
05-22-2009, 12:59 AM
Once again, this forum ate one of my answers.

It was too long, anyway.

Short and sweet: That code you are showing is a real hash.

It just makes almost no sense, at all. And you have all that stuff about background colors but then you never USE it. (Good thing, as it won't work as is, anyway.)

So no, this isn't a "small question". It's another rewrite. And first things first, we have to understand what you are trying to do. We *must* ignore your code, because it's just too wrong to use. And I tried to make sense of your question:
How do I use an array and an if function to tell thefinal variable which picture to display depending on what is selected, and save the selected image value to the cookie using saveImage() ?
But I can't.

Try again. Use English. No code. Tell us what you need that my code does *NOT* do.

ShadowIce
05-22-2009, 02:11 AM
Ok. to put it simply, how do I use an array to switch between different backgrounds using the <select> code?

TinyScript
05-22-2009, 03:44 AM
OP is the man! That's so sweet. I had not gotten around to understanding cookies so I really appreciate the working examples.

I'm a learn-by-working-with type of person so everything i had read about cookies before was hard to digest . Now I feel like I'll be able to reach the jar.

Old Pedant
05-22-2009, 06:25 AM
Okay, so I *THINK* you are just saying this:

Instead of "hard coding" the images into the <select> as I did with this code:


<select name="favSelect" onchange="getDivBG(this.value);">
<option value="">--choose--</option>
<option value="images/greenwhite_paper.gif">greenwhite</option>
<option value="images/teal_paper.gif">teal</option>
<option value="images/wind_paper.gif">blue</option>
<option value="images/peach_paper.gif">peach</option>
<option value="images/yellow_weave.gif">yellow-brown</option>
<option value="images/texturebackground.jpg">green textured</option>
</select>

You want to be able to put the images into a JavaScript array.

May I ask *WHY*?

If those image names are coming from some server-side code (e.g., PHP or ASP or JSP), they can just as easily be plopped directly into the <select> as into a JS array. So why mess with the array???

Where are you going to GET the JS array of image names *FROM*????

I'm not convinced you have any good reason to be doing this. But never mind. I'll play along with it.

Look here:
http://www.clearviewarts.com/cookiebgi2.html

The code that is changed:

At the top of the JS coding I have this:


<script>
/*
* Per Shadowice's request, the background image names are given
* in the following array, instead of just being placed in the HTML.
*/
var backgroundImages =
[ "images/greenwhite_paper.gif",
"images/teal_paper.gif",
"images/wind_paper.gif",
"images/peach_paper.gif",
"images/yellow_weave.gif",
"images/texturebackground.jpg" ];
var backgroundNames =
[ "greeen and white",
"teal",
"blue",
"peach",
"yellow-brown",
"textured green" ];

// And this code is used to load up the OPTIONs for the select:
function loadOptions( into )
{
for ( var b = 0; b < backgroundImages.length; ++b )
{
into.options[into.options.length] =
new Option( backgroundNames[b], backgroundImages[b] );
}
}

/*
* We now return you to our regularly scheduled programming
*/


And then we have to make sure that loadOptions code is called properly, so I do that via the body onload. And finally, I just changed the <select> to omit the options, as they will now be loaded from the arrays. So the body of the page changes to this (changes in red).


<body onload="getBodyBG(); loadOptions(document.TheForm.favSelect);">
<div id="mydiv" style="background-color: white; width: 120px; height: 120px;">
</div>
<form name="TheForm">
<select name="favSelect" onchange="getDivBG(this.value);">
<option value="">--choose--</option>
</select>
<input type="button" name="bg" value="Change Background" onClick="saveImage(this.form);">
</form>
</body>

The change to the initial background of the div isn't necessary, but it makes the actions clearer.

I think you can see that the net result is that the page is bigger, the code more complex (although not a lot so). And I really don't see that you've gained on darned thing.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum