<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Random Snippets &#187; onClick</title>
	<atom:link href="http://www.randomsnippets.com/tag/onclick/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.randomsnippets.com</link>
	<description>Random Snippets of Code and Ideas for any Web Developer</description>
	<lastBuildDate>Wed, 05 Aug 2009 14:32:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The dangers of embedding the notorious &#8220;void(0)&#8221; JavaScript code in the href attribute of the &#8220;a&#8221; tag</title>
		<link>http://www.randomsnippets.com/2009/04/08/the-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag/</link>
		<comments>http://www.randomsnippets.com/2009/04/08/the-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 04:50:27 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[ie bug]]></category>
		<category><![CDATA[onClick]]></category>
		<category><![CDATA[void]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/?p=212</guid>
		<description><![CDATA[I recent ran into an interesting IE bug involving the following bit of html code:

&#60;a href=&#34;javascript: void(0);&#34; onclick=&#34;dosomething();&#34;&#62;click me&#60;/a&#62;

I honestly did not write this one but I will leave names out of this to protect the innocent =)
The void(0) JavaScript code is usually used to prevent loading or reloading of the page when the user [...]]]></description>
			<content:encoded><![CDATA[<p>I recent ran into an interesting IE bug involving the following bit of html code:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;a href=&quot;javascript: void(0);&quot; onclick=&quot;dosomething();&quot;&gt;click me&lt;/a&gt;</pre></div></div>

<p>I honestly did not write this one but I will leave names out of this to protect the innocent =)</p>
<p>The <strong>void(0)</strong> JavaScript code is usually used to prevent loading or reloading of the page when the user clicks the link.  </p>
<p>What we were trying to do here was have the <strong>dosomething</strong> JavaScript function execute when a user clicks on the link.  This works fine in FireFox, Chrome, Safari but not IE.  When a user clicks on the link in IE, nothing happens: i.e. (no pun intended) the JavaScript does not execute.  </p>
<p>It took us a good amount of time to realize what the issue was with IE.  It turns out that the <strong>void(0)</strong> function was preventing the <strong>onclick</strong> event to fire.</p>
<p>Although it may not be pretty, this is what we ended up doing and it appears to be cross-browser friendly:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;a href=&quot;&lt;?=$_SERVER['PHP_SELF'];&gt;#&quot; onclick=&quot;dosomething();&quot;&gt;click me&lt;/a&gt;</pre></div></div>

<p>Anyway, I hope this helps someone out there in the universe.</p>

<script language="javascript" src="http://www.randomsnippets.com/wp-content/plugins/emailr/emailr.js"></script><script src="http://www.randomsnippets.com/wp-includes/js/jquery/jquery.js"></script>Share with a friend:<br /><input id="emailrRecipient" type="text" value="email address" onclick="this.value='';jQuery('#emailrResponse').html('');" style="color: #666;">&nbsp;&nbsp;<input id="emailrSendBtn" type="button" value="Send" onclick="this.disabled='true';sendEmail();jQuery('#emailrResponse').html('<image src=\'http://www.randomsnippets.com/wp-content/plugins/emailr/busy.gif\' />');">&nbsp;&nbsp;<div id="emailrResponse" style="display:inline;"></div><br />
<div style="clear: both;"></div>
<a id="customMsgLink" href="javascript:void(0);" onclick="jQuery('#customMessage').css('display','inline');jQuery('#customMsgLink').css('display',  'none');">Customize message</a><br />
<div id="customMessage" style="display: none;">
<input id="sender" type="text" value="your name" onclick="this.value='';" style="color: #666;">
<div style="clear: both;"></div>
<textarea rows="4" style="height: 100px;" id="emailrMessage" style="color: #666;">I think you might be interested in this: 

http://www.randomsnippets.com/2009/04/08/the-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag/
</textarea>
</div>
<div style="clear: both;"></div><br /><br />
<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.randomsnippets.com%2F2009%2F04%2F08%2Fthe-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag%2F&amp;title=The+dangers+of+embedding+the+notorious+%26%238220%3Bvoid%280%29%26%238221%3B+JavaScript+code+in+the+href+attribute+of+the+%26%238220%3Ba%26%238221%3B+tag" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2009/04/08/the-dangers-of-embedding-the-notorious-void0-javascript-code-in-the-href-attribute-of-the-a-tag/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to find and access parent nodes via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/06/26/how-to-find-and-access-parent-nodes-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/06/26/how-to-find-and-access-parent-nodes-via-javascript/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 06:15:53 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[dom tree]]></category>
		<category><![CDATA[findParentNode]]></category>
		<category><![CDATA[onClick]]></category>
		<category><![CDATA[onclick event]]></category>
		<category><![CDATA[parent node]]></category>
		<category><![CDATA[parent nodes]]></category>
		<category><![CDATA[parentName]]></category>
		<category><![CDATA[parentNode]]></category>
		<category><![CDATA[tagName]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/?p=19</guid>
		<description><![CDATA[
function findParentNode(parentName, childObj) {
    var testObj = childObj.parentNode;
    var count = 1;
    while(testObj.getAttribute('name') != parentName) {
        alert('My name is ' + testObj.getAttribute('name') + '. Let\'s try moving up one level to see what we get.');
     [...]]]></description>
			<content:encoded><![CDATA[<p><script language="javascript">
function findParentNode(parentName, childObj) {
    var testObj = childObj.parentNode;
    var count = 1;
    while(testObj.getAttribute('name') != parentName) {
        alert('My name is ' + testObj.getAttribute('name') + '. Let\'s try moving up one level to see what we get.');
        testObj = testObj.parentNode;
        count++;
    }
    // now you have the object you are looking for - do something with it
    alert('Finally found ' + testObj.getAttribute('name') + ' after going up ' + count + ' level(s) through the DOM tree');
}
</script><br />
Have you ever had to access a parent node from a given child node?  In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the <b>name</b> attribute <b>itsMe</b>.</p>
<fieldset>
<legend>Demo</legend>
<div name="notMe" style="padding:10px;border:1px solid green;">
My name is <b>notMe</b></p>
<div name="itsMe" style="padding:10px;border:1px solid blue;">
    My name is <b>itsMe</b></p>
<div name="notMeEither" style="padding:10px;border:1px solid red;">
        My name is <b>notMeEither</b></p>
<div name="tryAgain" style="padding:10px;border:1px solid purple;">
            My name is <b>tryAgain</b></p>
<div name="sorryNotMe" style="padding:10px;border:1px solid black;">
                My name is <b>sorryNotMe</b></p>
<div name="nopeSorry" style="padding:10px;border:1px solid brown;">
                    My name is <b>nopeSorry</b></p>
<input type="button" value="Find Parent Object with name=itsMe" onClick="findParentNode('itsMe', this);">
                    </div>
</p></div>
</p></div>
</p></div>
</p></div>
</div>
</fieldset>
<p><span id="more-19"></span><br />
Here is the HTML code.  It&#8217;s just a series of embedded div elements with different names and the input button where we start to traverse up the DOM tree accessing each parent node and asking for it&#8217;s name attribute value. The <b>onClick</b> event of the button triggers the <b>findParentNode</b> and passes the name of the element we are looking for and the object itself which, in this case, is the button.  This is the starting point where we will begin traversing up the DOM tree by accessing the parent nodes of each element and seeing if the name attribute matches what we are looking for.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;div name=&quot;notMe&quot; style=&quot;padding:10px;border:1px solid green;&quot;&gt;
My name is &lt;b&gt;notMe&lt;/b&gt;
    &lt;div name=&quot;itsMe&quot; style=&quot;padding:10px;border:1px solid blue;&quot;&gt;
    My name is &lt;b&gt;itsMe&lt;/b&gt;
        &lt;div name=&quot;notMeEither&quot; style=&quot;padding:10px;border:1px solid red;&quot;&gt;
        My name is &lt;b&gt;notMeEither&lt;/b&gt;
            &lt;div name=&quot;tryAgain&quot; style=&quot;padding:10px;border:1px solid purple;&quot;&gt;
            My name is &lt;b&gt;tryAgain&lt;/b&gt;
                &lt;div name=&quot;sorryNotMe&quot; style=&quot;padding:10px;border:1px solid black;&quot;&gt;
                My name is &lt;b&gt;sorryNotMe&lt;/b&gt;
                    &lt;div name=&quot;nopeSorry&quot; style=&quot;padding:10px;border:1px solid brown;&quot;&gt;
                    My name is &lt;b&gt;nopeSorry&lt;/b&gt;
                        &lt;input type=&quot;button&quot; value=&quot;Find Parent Object with name=itsMe&quot; onClick=&quot;findParentNode('itsMe', this);&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;</pre></td></tr></table></div>

<p>Here is the <b>findParentNode</b> JavaScript code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> findParentNode<span style="color: #009900;">&#40;</span>parentName<span style="color: #339933;">,</span> childObj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> testObj <span style="color: #339933;">=</span> childObj.<span style="color: #660066;">parentNode</span>;
    <span style="color: #003366; font-weight: bold;">var</span> count <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span>;
    <span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span>testObj.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'name'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> parentName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'My name is '</span> <span style="color: #339933;">+</span> testObj.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'name'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'. Let<span style="color: #000099; font-weight: bold;">\'</span>s try moving up one level to see what we get.'</span><span style="color: #009900;">&#41;</span>;
        testObj <span style="color: #339933;">=</span> testObj.<span style="color: #660066;">parentNode</span>;
        count++;
    <span style="color: #009900;">&#125;</span>
    <span style="color: #006600; font-style: italic;">// now you have the object you are looking for - do something with it</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Finally found '</span> <span style="color: #339933;">+</span> testObj.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'name'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">' after going up '</span> <span style="color: #339933;">+</span> count <span style="color: #339933;">+</span> <span style="color: #3366CC;">' level(s) through the DOM tree'</span><span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In line 2, we access the parent node of the child element via the <b>parentNode</b> method which is the first div above the button named <b>nopeSorry</b>.  We then begin a count of the number of times we traversed up the DOM tree and set it to 1 because we have already accessed the parent node once.  The while loop will test if the name of the current node will match the name that we are looking for.  If not, it moves up the DOM tree by accessing the next parent node and continues to look for the right name while increasing the count by 1 each time.  Once it finds the right node, the function exits the while loop and alerts the node name along with the number of times it traversed up the DOM tree.</p>
<p>If you do not know the name of the parent element you are looking for you can also search using the <b>tagName</b> method.  The tagName will return the value of the tag name of the given node such as <b>A</b> or <b>DIV</b>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/06/26/how-to-find-and-access-parent-nodes-via-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to dynamically add content to a div and store the content to a cookie via JavaScript</title>
		<link>http://www.randomsnippets.com/2008/04/14/how-to-dynamically-add-content-to-a-div-via-javascript/</link>
		<comments>http://www.randomsnippets.com/2008/04/14/how-to-dynamically-add-content-to-a-div-via-javascript/#comments</comments>
		<pubDate>Tue, 15 Apr 2008 06:45:17 +0000</pubDate>
		<dc:creator>Knix</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[add]]></category>
		<category><![CDATA[content]]></category>
		<category><![CDATA[cookieContent]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[demo content]]></category>
		<category><![CDATA[div id]]></category>
		<category><![CDATA[document cookie]]></category>
		<category><![CDATA[document getelementbyid]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[dynamic content]]></category>
		<category><![CDATA[Dynamically]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[getCookie]]></category>
		<category><![CDATA[getElementById]]></category>
		<category><![CDATA[input text]]></category>
		<category><![CDATA[javascript code]]></category>
		<category><![CDATA[javascript function]]></category>
		<category><![CDATA[javascript functions]]></category>
		<category><![CDATA[onClick]]></category>
		<category><![CDATA[setCookie]]></category>
		<category><![CDATA[store content]]></category>

		<guid isPermaLink="false">http://www.randomsnippets.com/?p=14</guid>
		<description><![CDATA[
function addContent(divName, content) {
     document.getElementById(divName).innerHTML = content;
}
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 + "=");
     [...]]]></description>
			<content:encoded><![CDATA[<p><script lang="javascript">
function addContent(divName, content) {
     document.getElementById(divName).innerHTML = content;
}
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;
        } 
    }
}
</script><br />
This is an example of adding dynamic content via JavaScript by allowing the user type in the actual content.</p>
<fieldset>
<legend>Demo</legend>
<form name="myForm">
Content to be added:<br />
<textarea name="myContent">Type here&#8230;<br />
<h1>tags work as well</h1>
<p><u>woohoo</u></textarea></p>
<input type="button" value="Add content" onClick="addContent('myDiv', document.myForm.myContent.value)">
</form>
<p>Your content will be added dynamically below:</p>
<div id="myDiv"></div>
</fieldset>
<p><span id="more-14"></span><br />
Here is the plain HTML for the demo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;form name=&quot;myForm&quot;&gt;
Content to be added:
&lt;textarea name=&quot;myContent&quot;&gt;Type here...&lt;h1&gt;tags work as well&lt;/h1&gt;&lt;u&gt;woohoo&lt;/u&gt;&lt;/textarea&gt;
&lt;input type=&quot;button&quot; value=&quot;Add content&quot; onClick=&quot;addContent('myDiv', document.myForm.myContent.value); setCookie('content', document.myForm.myContent.value, 7);&quot;&gt;
&lt;/form&gt;
&lt;br&gt;&lt;br&gt;
Your content will be added dynamically below:
&lt;div id=&quot;myDiv&quot;&gt;&lt;/div&gt;</pre></td></tr></table></div>

<p>There are 3 important parts to the HTML code:</p>
<ol>
<li><b>textarea</b> &#8211; This is the content that the user enters.  HTML tags are naturally supported.</li>
<li><b>Add content button</b> &#8211;  This buttons calls our <b>addContent()</b> function which passes the div id of where the content is to be entered and the actual content itself from the <b>textarea</b>.</li>
<li><b>myDiv</b> &#8211; This is the id of blank div where the content will be inserted.</li>
</ol>
<p>Here is the JavaScript code for the <b>addContent()</b> function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> addContent<span style="color: #009900;">&#40;</span>divName<span style="color: #339933;">,</span> content<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span>divName<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> content;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>That&#8217;s it!  All it does it retrieve the DOM element, which in this case, is just an empty div and sets the <b>innerHTML</b> attribute to the content that is passed over to this function from the form.  </p>
<p>This demo is in response to a request that saves the content that the user has entered.</p>
<fieldset>
<legend>Demo</legend>
<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.</p>
<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>
<p>Your name will be saved below:</p>
<div id="myDiv2" style="font-weight: bold;"></div>
</fieldset>
<p>Here is the HTML code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;form name=&quot;myForm2&quot;&gt;
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.
&lt;br&gt;&lt;br&gt;
&lt;input text name=&quot;myContent2&quot; value=&quot;Enter your name here...&quot;&gt;
&lt;input type=&quot;button&quot; value=&quot;Save my name&quot; onClick=&quot;addContent('myDiv2', document.myForm2.myContent2.value); setCookie('content', document.myForm2.myContent2.value, 7);&quot;&gt;
&lt;/form&gt;
&lt;br&gt;&lt;br&gt;
Your name will be saved below:
&lt;div id=&quot;myDiv2&quot; style=&quot;font-weight: bold;&quot;&gt;&lt;/div&gt;</pre></td></tr></table></div>

<p>The <b>onClick</b> event listener will launch 2 scripts this time:</p>
<ol>
<li><b>addContent</b> &#8211; This will do exactly what it did before in the first demo and just insert the input text value inside the div.</li>
<li><b>setCookie</b> &#8211; This will save a cookie with the name <b>content</b> and assign whatever is inside the input text as the value.  In addition, the cookie is set to expire in 7 days.</li>
</ol>
<p>To avoid reinventing the wheel, I have borrowed the JavaScript get and set cookie functions from <a href="http://www.w3schools.com/JS/js_cookies.asp" target="_blank">W3 Schools</a> and edited it slightly for the needs of this demo.</p>
<p>Here are the new JavaScript functions for cookie management:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> setCookie<span style="color: #009900;">&#40;</span>c_name<span style="color: #339933;">,</span>value<span style="color: #339933;">,</span>expiredays<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> exdate<span style="color: #339933;">=</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
    exdate.<span style="color: #660066;">setDate</span><span style="color: #009900;">&#40;</span>exdate.<span style="color: #660066;">getDate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span>expiredays<span style="color: #009900;">&#41;</span>;
    document.<span style="color: #660066;">cookie</span><span style="color: #339933;">=</span>c_name<span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span> <span style="color: #339933;">+</span>escape<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>expiredays<span style="color: #339933;">==</span><span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> <span style="color: #3366CC;">&quot;&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;;expires=&quot;</span><span style="color: #339933;">+</span>exdate.<span style="color: #660066;">toGMTString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> getCookie<span style="color: #009900;">&#40;</span>c_name<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">length</span><span style="color: #339933;">&gt;</span>0<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        c_start<span style="color: #339933;">=</span>document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span>c_name <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span><span style="color: #009900;">&#41;</span>;
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c_start<span style="color: #339933;">!=-</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
            c_start<span style="color: #339933;">=</span>c_start <span style="color: #339933;">+</span> c_name.<span style="color: #660066;">length</span><span style="color: #339933;">+</span><span style="color: #CC0000;">1</span>; 
            c_end<span style="color: #339933;">=</span>document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;;&quot;</span><span style="color: #339933;">,</span>c_start<span style="color: #009900;">&#41;</span>;
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c_end<span style="color: #339933;">==-</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span> c_end<span style="color: #339933;">=</span>document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">length</span>;
            <span style="color: #003366; font-weight: bold;">var</span> cookieContent <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Welcome back &quot;</span> <span style="color: #339933;">+</span> unescape<span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span>c_start<span style="color: #339933;">,</span>c_end<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
            document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'myDiv2'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> cookieContent;
        <span style="color: #009900;">&#125;</span> 
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
getCookie<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'content'</span><span style="color: #009900;">&#41;</span>;</pre></td></tr></table></div>

<p>Please refer to <a href="http://www.w3schools.com/JS/js_cookies.asp" target="_blank">W3 Schools</a> for a detailed description of these JavaScript functions.  The only edit I have made is with the <b>getCookie</b> 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 <b>getCookie</b> function and looks for the <b>content</b> cookie.  If the cookie exists, the content will be displayed in the <b>myDiv2</b> div.  </p>
<p>When using these JavaScripts, <b> make sure you load them after all your HTML is loaded</b>.  Otherwise, the function would have no place to insert the cookie content.</p>
<p>Although using cookies is a great way to store information, there are a couple of caveats:</p>
<ol>
<li><b>Size limitation</b> &#8211; This depends on the browser but keeping your cookies to a maximum size of 4000 bytes will keep you in the safe zone.</li>
<li><b>Cookie limit per domain</b> &#8211; This also depends on the browser but the general rule is 20 cookies per domain.</li>
</ol>
<p><script lang="javascript">getCookie('content');</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.randomsnippets.com/2008/04/14/how-to-dynamically-add-content-to-a-div-via-javascript/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
