0

I am trying to learn cookies in JavaScript. I have already made it possible to save a text as a cookie and view the what is inside the cookie on another page.

What I would like to do now is to make another box like the one I have before but in this box I want to enter rgb color code which will give the cookie page 2 the color which has been saved in the cookie by the user. Hope you understood my question and can help me as much as possible.

Here is my code:

Cookie Page 1:

<!doctype html>

<html>

<head>

<meta name="viewport" content="width=device-width">
<meta charset="utf-8">

<title>Cookies side 1</title>

</head>

<body>

<nav>
<ul>
    <li><a href="cookies1.html">Cookies 1</a></li>
    <li><a href="cookies2.html">Cookies 2</a></li>
</ul>
</nav>

<section id="cookieadmin">
<h3>Save/Delete a cookie</h3>
<label>Write a text
    <input id="textTxt" type="text" placeholder="...write here">
</label>
<input id="saveCookieBtn" type="button" value="Save cookie">
<input id="deleteCookieBtn" type="button" value="Delete cookie">
<p id="cookiestatus"></p>
</section>

<script>
(function(){

var textTxt;
var saveCookieBtn, deleteCookieBtn;
var cookiestatus;

function init(){
    setHTMLObjects();
    setEvents();

    checkIfCookieExists();
}
function setEvents(){
    saveCookieBtn.addEventListener("click", saveCookie);        
    deleteCookieBtn.addEventListener("click", deleteCookie);
}
function deleteCookie(){
    var dateObject = new Date();
    dateObject.setDate(dateObject.getDate() - 1);

    document.cookie = "text=;expires=" + dateObject.toUTCString();

    checkIfCookieExits();
}
function saveCookie(){
    var dateObject = new Date();
    dateObject.setDate(dateObject.getDate() + 7);

    document.cookie = "text=" + textTxt.value + ";expires=" + dateObject.toUTCString();

    checkIfCookieExists();
}
function setHTMLObjects(){
    textTxt = document.getElementById("textTxt");
    saveCookieBtn = document.getElementById("saveCookieBtn");
    deleteCookieBtn = document.getElementById("deleteCookieBtn");
    cookiestatus = document.getElementById("cookiestatus");
}

function checkIfCookieExists(){
    var message;


    if(document.cookie){
        message = "Cookie exists";
    }else
    {
        message = "Cookie does not exist";
    }

    cookiestatus.innerHTML = message;
}

window.onload = init;
}())
</script>

</body>
</html>

Cookie Page 2:

<!doctype html>

<html>

<head>

<meta name="viewport" content="width=device-width">
<meta charset="utf-8">

<title>Cookie 2s</title>

</head>

<body>

<nav>
<ul>
    <li><a href="cookies1.html">Cookies 1</a></li>
    <li><a href="cookies2.html">Cookies 2</a></li>
</ul>
</nav>

<p id="cookiestatus"></p>
<script>
(function(){

var cookiestatus;
function init(){
    setHTMLObjects();
    checkIfCookieExists();
}
function setHTMLObjects(){
    cookiestatus = document.getElementById("cookiestatus");
}
function checkIfCookieExists(){
    var message;
    if(document.cookie){

        var cookielist = document.cookie.split("=");
        var value = cookielist[1];

        message = "Cookie exists: " + value;
    }else
    {
        message = "Cookie does not exist";
    }
    cookiestatus.innerHTML = message;
}
window.onload = init;
}())
</script>

</body>
</html>

2 Answers2

0

You can create an textbox input element where the user can enter the hexadecimal color value they desire for that page, and store its value as the cookie. Since you already have the functions that handle cookie setting and getting, here's a sample of how you could retrieve the color value.

var input = document.getElementById("colorInput");
input.addEventListener("keydown", function() {
  setTimeout(function() {
    document.getElementById("value").innerHTML = input.value;
    }, 500);
});
<input id="colorInput" type="text" />
<p>Input value: <span id="value"></span></p>

You would also have to add some kind of validation check on input value to make sure it's a proper hex value. As for the cookie itself, you could store all colors for different pages as a stringified JSON object at the root level, or set different cookies at each page level, in which case mind the names you use for each one of them.

Edit:

I made a demo of how your code could work. Here's the code for each page.

Page 1:

<html>

<head>

<meta name="viewport" content="width=device-width">
<meta charset="utf-8">

<title>Cookies side 1</title>

</head>

<body>

<nav>
<ul>
    <li><a href="cookies1.html">Cookies 1</a></li>
    <li><a href="cookies2.html">Cookies 2</a></li>
</ul>
</nav>

<section id="cookieadmin">
<h3>Save/Delete a cookie</h3>
<label>Write a text
    <input id="textTxt" type="text" placeholder="...write here">
</label>
<input id="saveCookieBtn" type="button" value="Save cookie">
<input id="deleteCookieBtn" type="button" value="Delete cookie">
<input id="colorInput" type="text" />
<input id="saveColorBtn" type="button" value="Save color" /><span id="valMsg"></span>
<p>Input color: <span id="colorValue">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></p>
<p id="cookiestatus"></p>
</section>

<script>

function init() {
    setHTMLObjects();
    setEvents();
    checkIfCookieExists();
}

function setEvents() {
    saveCookieBtn.addEventListener("click", saveCookie);        
    deleteCookieBtn.addEventListener("click", deleteCookie);
    saveColorBtn.addEventListener("click", saveColor);
}

function deleteCookie() {
    var dateObject = new Date();
    dateObject.setDate(dateObject.getDate() - 1);
    document.cookie = "text=;expires=" + dateObject.toUTCString();
    checkIfCookieExits();
}

function saveCookie() {
    var dateObject = new Date();
    dateObject.setDate(dateObject.getDate() + 7);
    document.cookie = "text=" + colorInput.value + ";expires=" + dateObject.toUTCString();
    checkIfCookieExists();
}

function setHTMLObjects(){
    textTxt = document.getElementById("textTxt");
    saveCookieBtn = document.getElementById("saveCookieBtn");
    deleteCookieBtn = document.getElementById("deleteCookieBtn");
    cookieStatus = document.getElementById("cookiestatus");
    colorInput = document.getElementById("colorInput");
    colorValue = document.getElementById("colorValue");
    saveColorBtn = document.getElementById("saveColorBtn");
    valMsg = document.getElementById("valMsg");
}

function checkIfCookieExists() {
    var message;
    if (document.cookie) {
        message = "Cookie exists";
    } else {
        message = "Cookie does not exist";
    }
    cookiestatus.innerHTML = message;
}

function saveColor() {
    var color = colorInput.value,
        msg;
    if( isHex(color) ) {
        color = '#'+color;
        msg = '<em style="color:green;">Valid hex value!</em>';
        colorValue.innerHTML = color;
        document.body.style.background = color;
        saveCookie();
    } else {
        colorInput.value = '';
        msg = '<em style="color:red;">Invalid hex value!</em>';
    }
    valMsg.innerHTML = msg;
    setTimeout(function() {
        valMsg.innerHTML = "";
    }, 5000);
}

function isHex(str) {
    /* Author: Royi Namir
     * Ref: http://stackoverflow.com/questions/8027423/how-to-check-if-a-string-is-a-valid-hex-color-representation#answer-8027444
    */
    var isHex = /(^[0-9A-F]{6}$)|(^[0-9A-F]{3}$)/i.test(str);
    return isHex;
}

var saveCookieBtn, deleteCookieBtn, saveColorBtn, cookiestatus, colorInput;

window.addEventListener("load", init, false);

Page 2:

<!doctype html>

<html>

<head>

<meta name="viewport" content="width=device-width">
<meta charset="utf-8">

<title>Cookie 2s</title>

</head>

<body>

<nav>
<ul>
    <li><a href="cookies1.html">Cookies 1</a></li>
    <li><a href="cookies2.html">Cookies 2</a></li>
</ul>
</nav>

<p id="cookiestatus"></p>
<script>
(function(){

var cookiestatus;
function applyCookieColor() {
    var color = getCookie();
    // Change text color of element
    elemColor.style.color = color;
    // OR change background color of element
    elemColor.style.backgroundColor = color;
}
function init(){
    setHTMLObjects();
    checkIfCookieExists();
    applyCookieColor();
}
function setHTMLObjects(){
    cookiestatus = document.getElementById("cookiestatus");
    elemColor = document.getElementById("elemColor");
}
function checkIfCookieExists(){
    var message;
    if(document.cookie){

        var cookielist = document.cookie.split("=");
        var value = cookielist[1];

        message = "Cookie exists: " + value;
    }else
    {
        message = "Cookie does not exist";
    }
    cookiestatus.innerHTML = message;
}
function getCookie() {
    /* code to get the cookie */
}

window.onload = init;
}());
</script>

</body>
</html>

Note: For the JS code in Page 2 to work properly, you need to complete the getCookie() function, which I left blank since I assume you already got it.

Edit 2:

I found a really complete cookie handling script in the https://developer.mozilla.org site. You should use it for cookie handling.

JS:

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};
Marventus
  • 864
  • 1
  • 7
  • 14
  • We are just talking about 1 subpage where this color cookie will work, not a new page per cookie. Hope u understand what I mean... – user3564474 Dec 20 '14 at 16:28
  • The javascript code you gave me, where should it be placed? I have added the HTML code... – user3564474 Dec 20 '14 at 16:39
  • Could you please add it in my code and make a snippet? – user3564474 Dec 20 '14 at 17:05
  • Sure. Which page will the box to select the color be added to: 1 or 2? – Marventus Dec 20 '14 at 17:18
  • Page 1 is the main page, and the color should be applied on the page 2. – user3564474 Dec 20 '14 at 17:34
  • I updated my answer with a demo. Will update again with the proper code in a few minutes. – Marventus Dec 20 '14 at 19:13
  • The method I have to get the cookie is to check if the cookie exits and if yes, then the cookie will appear, if not then nothing will appear. Please take a look at this: checkIfCookieExists – user3564474 Dec 21 '14 at 10:20
  • That function checks whether the cookie exists, but doesn't return the cookie value, i.e., the color stored in Page 1. If you want to do that, you need to retrieve the actual value of the cookie. If you are having trouble doing that, I suggest (if it's a possibility) to use jQuery along with a jQuery plugin called jQuery.cookie. – Marventus Dec 21 '14 at 14:39
  • Thanks for your reply. I am just stuck! I have been waiting for more help from you. I can only use javaScript... – user3564474 Dec 21 '14 at 15:35
  • Ok, I'll try to expand my answer so that you can also retrieve the color stored in that cookie. – Marventus Dec 21 '14 at 17:52
  • I just updated my answer (check out Edit 2) with a script that will definitely be of help to you. – Marventus Dec 22 '14 at 12:18
  • Never heard back from you after my edit. Everything ok? – Marventus Dec 23 '14 at 13:44
-1

All modern browsers support LocalStorage, use it instead.

To save data use

var myVar = localStorage.setItem('myVar', 'myValue');

To get data:

var myVar = localstorage.getItem('myVar'); // will get 'myValue'

To check compatibility for old versions use:

if(typeof(Storage)!=='undefined') {
    // you code here
} else {
    // Oops, no Local Storage
}

Have fun!

nnn
  • 328
  • 3
  • 9