0

I'm trying to make a simple program that stores the h1 value in a variable and then store it in a cookie. But whenever I reload the page the h1 value always goes back to 0 and is not being saved. Can someone please explain how I can save the variable in a cookie so when I reload the page it stays there.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>
    <div class="container">
        <h1 id="hs">1 </h1> <img src="image01.jpg" width="960" height="640" />
        <button onclick="increase()" id="d">Increase value of cookie</button>
    </div>
    <script src="cookies.min.js"></script>
    <script>
        Cookies.set('name', 'leo');
        Cookies.set('nams', 'ddleo');
        var h = document.getElementById("hs");

        function increase() {
            var values = parseInt(document.getElementById('hs').innerHTML, 10);
            values++;
            Cookies.set("name", values);
            document.getElementById('hs').innerHTML = Cookies.get("name", values);
        }
    </script>
</body>

</html>

2 Answers 2

2

When the page loads, you need to replace the <h1> with the value from the cookie.

var h=document.getElementById("hs");
var value = Cookies.get('name');
if (value) {
    h.innerHTML = value;
}
Sign up to request clarification or add additional context in comments.

Comments

0

When you refresh the page, the DOM doesn't know anything about the value of that cookie. It needs to be explicitly set.

This line:

document.getElementById('hs').innerHTML=Cookies.get("name",values);

should be run on page load, before you define the function increase:

var h = document.getElementById("hs");

# initial setting of h1:
var initialValue = Cookies.get("name",values);

if(initialValue) {
  h.innerHTML = initialValue;
}

function increase(){
  # dynamic setting of h1 (via the click handler you set up)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.