Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post

    Need help with background cookie function..

    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:

    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~

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,184
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Would have found this quickly if you'd used a debugger.

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

    Now try:
    Code:
    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.

  • #3
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    Ok. I fixed what I could. But it still returns an invalid argument.

    Code:
    <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?
    Last edited by ShadowIce; 05-19-2009 at 01:54 PM.

  • #4
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    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:

    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~

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,184
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    This line is illegal:
    Code:
    <body background="GetCookie('image');">
    You can't call a function from a property. Only from an *event*.

    Try this:
    Code:
    <body onload="image();">

  • #6
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    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:

    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~

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,184
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    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:
    Code:
    <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>.

  • Users who have thanked Old Pedant for this post:

    TinyScript (05-22-2009)

  • #8
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    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.

    Code:
    <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~

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,184
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    No, you STILL have bad JS in there.

    Try something like this:
    Code:
    <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.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,184
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Here, a working demo, with images:

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

  • The Following 2 Users Say Thank You to Old Pedant For This Useful Post:

    ShadowIce (05-20-2009), TinyScript (05-22-2009)

  • #11
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    Dude! Its PERFECT! Thank you SO much for all your help!

  • #12
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    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:

    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~
    Last edited by ShadowIce; 05-20-2009 at 04:34 PM.

  • #13
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    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~

  • #14
    Regular Coder
    Join Date
    Apr 2009
    Posts
    264
    Thanks
    24
    Thanked 1 Time in 1 Post
    Can someone please help? This is the last question I have about cookies....

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,184
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    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.


  •  
    Page 1 of 2 12 LastLast

    LinkBacks (?)


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •