How to read a JavaScript cookie?

831 views Asked by At

I want to output a random number from JavaScript function that will be saved in cookie and will be called at the end of the application?

  <script>
    document.getElementById("demo").innerHTML = Math.floor(Math.random()*50)*2;
   document.cookie="document.getElementById("demo").value";

</script>

<script>
      var x = document.value;
  document.getElementById("number").innerHTML = "x"
</script>
2

There are 2 answers

0
Cristobal On

This is from Mozilla Document.cookie docs:

document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
alert(document.cookie);
// displays: name=oeschger;favorite_food=tripe
6
chris97ong On

Check out the W3Schools tutorial on cookies. As for your case, this is how you implement it:

<!-- Start of the Application -->
<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50)*2;

// Following functions from W3Schools
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

// set a cookie "number" to the `innerHTML` of the element with Id `demo`.
setCookie("number",document.getElementById("demo").innerHTML,365);
</script>

<!-- End of the application -->
<script>
// get the value of the cookie "number" that was set earlier
var x = getCookie("number");

// Change the Id to whatever you need
document.getElementById("whatever").innerHTML = x;
</script>