0

I need help with saving the input to cookies and displaying it to the user. I need to make the text in the input to change into the div and display the same text for the user every time he visits the page.

Now I have just the input because I really don't know how to make it.

HTML

<input type="text" class="name" placeholder="What's your name?"/>

CSS

@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed:700');
.name{
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 3.5vw;
    border: 0;
    outline:0;
    background: transparent;
    border-bottom: 2px solid white;
    width: 30%;
    color:#000000;
    position:fixed;
    top:60%;
    left:50%;
    margin-left:10px;
}

Thanks for your the help

joka00
  • 2,357
  • 1
  • 10
  • 27

1 Answers1

0

I would recommend setting the cookie with your backend (e.g PHP). However, if you want to only use client-side implementation, you can use js.cookie library.

Here is a simple working code that uses Cookies written and read by javascript only. It listens to the keydown event, so that every letter typed into the input automatically updates the cookie.

Important: Make sure you use a webserver when running it (for example: http://localhost/index.html and not file://c:/index.html. Otherwise cookies won't work.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.3/js.cookie.js"></script>
<body>
    <input id="name" type="text" class="name" placeholder="What's your name?"/>

    <script>
        $(document).ready(function(){
            var name = Cookies.get('_username');
            if (name) {
                $('#name').val(name);
            }
            $('#name').keydown(function(){
                var inputName = $('#name').val();
                Cookies.set('_username', inputName);
            })
        });
    </script>
</body>
</html>
Z-Bone
  • 1,534
  • 1
  • 10
  • 14