How to dynamically add content to a div and store the content to a cookie via JavaScript


This is an example of adding dynamic content via JavaScript by allowing the user type in the actual content.

Demo
Content to be added:

Your content will be added dynamically below:


Here is the plain HTML for the demo:

1
2
3
4
5
6
7
8
<form name="myForm">
Content to be added:
<textarea name="myContent">Type here...<h1>tags work as well</h1><u>woohoo</u></textarea>
<input type="button" value="Add content" onClick="addContent('myDiv', document.myForm.myContent.value); setCookie('content', document.myForm.myContent.value, 7);">
</form>
<br><br>
Your content will be added dynamically below:
<div id="myDiv"></div>

There are 3 important parts to the HTML code:

  1. textarea – This is the content that the user enters. HTML tags are naturally supported.
  2. Add content button – This buttons calls our addContent() function which passes the div id of where the content is to be entered and the actual content itself from the textarea.
  3. myDiv – This is the id of blank div where the content will be inserted.

Here is the JavaScript code for the addContent() function:

1
2
3
function addContent(divName, content) {
     document.getElementById(divName).innerHTML = content;
}

That’s it! All it does it retrieve the DOM element, which in this case, is just an empty div and sets the innerHTML attribute to the content that is passed over to this function from the form.

This demo is in response to a request that saves the content that the user has entered.

Demo
Enter your name below and click the button. Your name will be saved to a cookie that expires in 7 days. When you refresh the page or come back to visit you will see a heartwarming message welcoming you back.

Your name will be saved below:

Here is the HTML code:

1
2
3
4
5
6
7
8
9
<form name="myForm2">
Enter your name below and click the button.  Your name will be saved to a cookie that expires in 7 days.  When you refresh the page or come back to visit you will see a heartwarming message welcoming you back.
<br><br>
<input text name="myContent2" value="Enter your name here...">
<input type="button" value="Save my name" onClick="addContent('myDiv2', document.myForm2.myContent2.value); setCookie('content', document.myForm2.myContent2.value, 7);">
</form>
<br><br>
Your name will be saved below:
<div id="myDiv2" style="font-weight: bold;"></div>

The onClick event listener will launch 2 scripts this time:

  1. addContent – This will do exactly what it did before in the first demo and just insert the input text value inside the div.
  2. setCookie – This will save a cookie with the name content and assign whatever is inside the input text as the value. In addition, the cookie is set to expire in 7 days.

To avoid reinventing the wheel, I have borrowed the JavaScript get and set cookie functions from W3 Schools and edited it slightly for the needs of this demo.

Here are the new JavaScript functions for cookie management:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function setCookie(c_name,value,expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            var cookieContent = "Welcome back " + unescape(document.cookie.substring(c_start,c_end));
            document.getElementById('myDiv2').innerHTML = cookieContent;
        } 
    }
}
getCookie('content');

Please refer to W3 Schools for a detailed description of these JavaScript functions. The only edit I have made is with the getCookie function in lines 13-14 where it retrieves the cookie value and inserts the content into a div. Also, line 18 is very important as it calls the getCookie function and looks for the content cookie. If the cookie exists, the content will be displayed in the myDiv2 div.

When using these JavaScripts, make sure you load them after all your HTML is loaded. Otherwise, the function would have no place to insert the cookie content.

Although using cookies is a great way to store information, there are a couple of caveats:

  1. Size limitation – This depends on the browser but keeping your cookies to a maximum size of 4000 bytes will keep you in the safe zone.
  2. Cookie limit per domain – This also depends on the browser but the general rule is 20 cookies per domain.