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. <form name="myForm">
    
  2. Content to be added:
    
  3. <textarea name="myContent">Type here...<h1>tags work as well</h1><u>woohoo</u></textarea>
    
  4. <input type="button" value="Add content" onClick="addContent('myDiv', document.myForm.myContent.value); setCookie('content', document.myForm.myContent.value, 7);">
    
  5. </form>
    
  6. <br><br>
    
  7. Your content will be added dynamically below:
    
  8. <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. function addContent(divName, content) {
  2.      document.getElementById(divName).innerHTML = content;
  3. }

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. <form name="myForm2">
    
  2. 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.
    
  3. <br><br>
    
  4. <input text name="myContent2" value="Enter your name here...">
    
  5. <input type="button" value="Save my name" onClick="addContent('myDiv2', document.myForm2.myContent2.value); setCookie('content', document.myForm2.myContent2.value, 7);">
    
  6. </form>
    
  7. <br><br>
    
  8. Your name will be saved below:
    
  9. <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. function setCookie(c_name,value,expiredays) {
  2.     var exdate=new Date();
  3.     exdate.setDate(exdate.getDate()+expiredays);
  4.     document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
  5. }
  6. function getCookie(c_name) {
  7.     if (document.cookie.length>0) {
  8.         c_start=document.cookie.indexOf(c_name + "=");
  9.         if (c_start!=-1) { 
  10.             c_start=c_start + c_name.length+1; 
  11.             c_end=document.cookie.indexOf(";",c_start);
  12.             if (c_end==-1) c_end=document.cookie.length;
  13.             var cookieContent = "Welcome back " + unescape(document.cookie.substring(c_start,c_end));
  14.             document.getElementById('myDiv2').innerHTML = cookieContent;
  15.         } 
  16.     }
  17. }
  18. 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.

Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

20 thoughts on “How to dynamically add content to a div and store the content to a cookie via JavaScript”

  1. Hi, I would like to save the cookie forever without making it expire. Also I would like to display multiple cookies in a combobox or selection. Help me with this please

    1. Hi Guillermo,

      You cannot set a cookie that doesn’t expire as the specifications require a date. You can set it to expire in 10 years though (as an example):

      var CookieDate = new Date;
      CookieDate.setFullYear(CookieDate.getFullYear( ) +10);
      document.cookie = 'myCookie=to_be_deleted; expires=' + CookieDate.toGMTString( ) + ';';

      This code snippet is from StackOverflow: http://stackoverflow.com/questions/6348377/how-to-set-a-javascript-cookie-to-expire-in-10-years

  2. Sorry but I couldn’t reply to the other thread, don’t know why. I’m not sure I know what you mean. I’ve used your function on the link:
    addContent(‘texto_01’, get(“texto_01”,1,1,1,$page->ID) )
    The value is fetched using get from a custom field.
    The script is placed on my header file and functions.php should be able to find it like I did with the Showhide script, right?

    1. Hi S3nd41,

      I think I know the issue you are having now. The addContent() function is a JavaScript function and you are using it as a PHP function which leads to the fatal error that you see. You will need to add the following JavaScript function to your WordPress:

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

      Then, you will need to call this function in your JavaScript code, not your PHP code like you have in pastebin code.

      I hope this leads you in the right direction.

      Allen

      1. Hi Allen, actually I got it to work in the meantime, it was a syntax error on the PHP code, it had to be written like this:

        addContent(‘ . “‘texto_01’,'” . get(‘texto_01’,1,1,1,$page->ID) . ‘);

        Now it’s working perfectly, thank you very much for your help!

  3. Strange… I’m using a WordPress blog and I’ve added the javascript code to my header.php and tried to call it from my functions.php and got a “Fatal error: Call to undefined function addContent()”.

    Does anyone know what I might be doing wrong?

    1. Hi S3nd41,

      Very strange issue indeed. One would assume that if JavaScript code makes it into the header.php file in WordPress, that it should be available on all pages. Your issue sounds like it did not make it though. Did you confirm that the JavaScript code is not in your raw HTML? Can you give me a link to a sample page that illustrates this problem?

      Allen

        1. Hi S3nd41,

          It looks like the issue you are having is separate from your edit to the header.php file. I can see that your JavaScript code is there. This is a PHP issue where you are calling addContent() function but it has not been defined or loaded. Have you confirmed that your addContent() function is there? Is this a custom function or a WordPress function?

          Allen

            1. Hi S3nd41,

              I do not see the addContent() PHP function defined in your file which is the one causing the issue.

              Allen

  4. Did anyone ever find out how to use the cookie to retrieve the users last hidden/shown divs ?

    I’ve seen tutorials for names etc, but nothing yet on how to keep toggled settings.

    I’m looking for toggle2 settings to be kept.

    Thanks for any pointers!

  5. Hey,
    Is there a way to save the contents of a (all of the inside) with cookies and then when the page loads, open the cookie and display the saved data as the ‘s inside the tag?

    Also, the user updates the cookie with a link?

    Please help.. i would greatly appreciate it :)

  6. Nifty! Worked the first time!

    QUESTION, though.

    While making specific use of it I stumbled into a problem that I hope someone can help on. This may not be the best/only way to skin this cat, but we have a PHP/MySQL page that has to be modified to ADD rows for data entry when needed. I have abandoned the traditional DOM object methods of adding a single row, since in this case the addition would be a whole block of rows. I don’t think I’m smart enough to do that…

    Anyway, an idea hit me to make use of our MySQL dB and store the rows in there, and retrieve them using your method.

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

    Content to be added:

    Your content will be added dynamically below:

    Skipping an ultimate requirement that the content of the addition needs to be invisible and inaccessible, I tried the above out. It works, but the variable ($_value) has form elements in it, including . The close of the tag, interrupts the value and throws the remaining code to the page, not awaiting insertion by the Submit Button.

    Example: http://www.facey.com/insert_content1.php

    The Submit button successfully produces the part that stayed inside, but you see my problem.

    IS THERE A WAY to use this javascript addContent function, incorporate the utility of an ADD button, and avoid using the packaging of FORMS?

    Thanks for any help!

    p.s. The PHP component is transparent. Direct inclusion of the HTML contained in the variable as the value of TEXTAREA produces the same result.

  7. Is there a way to save this content so that next time when a user opens the page, it should be the new content.

    1. Hi suresh babu,

      You sure can save the content. There are several ways to do this and I will try to think of the simplest way and post an answer by this evening.

Leave a Reply

Your email address will not be published. Required fields are marked *