JavaScript Video Tutorial Pt 9

JavaScript CookiesIn this JavaScript Video Tutorial, I show you how to create, change, delete and retrieve the values in JavaScript cookies.

I also review some useful string functions and other ways to use the Document Object Model.

If you missed previous versions of this video tutorial, it all started with this JavaScript Video Tutorial Part 1. By the end of this tutorial you’ll not only understand how to do anything with cookies, you’ll also have an intimate knowledge of the DOM.

All of the code used follows the video below. You can use it as a cheat sheet for how to interact with Cookies in JavaScript, because it is heavily commented.

Code From the Video

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>

<html xmlns=””>


<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />

<title>Javascript Cookies</title>

<script type=”text/javascript”>

// Cookies are used to store information on the clients hard drive

// You can only access the information you stored on the clients machine

// You can’t access other websites cookies

// Cookies contain a name, value, expiration, directory that can access it and the domain that can access it

function getACookie(name)


var cookieName = document.getElementById(“getme”).value;     // Get the value from the text box called getme

var allCookies = document.cookie.split(‘;’);      // Splits all of the cookies and puts them in an array

var cookieData = “”;

for (var i=0; i < allCookies.length; i++)     // Cycle through all of the cookies in the array


if ((allCookies[i].indexOf(cookieName)) != -1)      // Test to see if string contains the cookie name


match = allCookies[i].replace(” “, “”);     // Deletes whitespace that may proceed the cookie name

cookieData = match.substr((cookieName.length + 1));     // Assign the substring that follows the cookie name

alert(cookieName + ” ” + cookieData);




function createCookie(newCookie)


var expDate = new Date();

expDate.setMonth(expDate.getMonth() + 1);     // Adds 1 month ahead as the expiration date

var cookieVal = document.getElementById(newCookie).value;

// Retrieves cookie value from the node that was past to the function

document.cookie = newCookie + “=” + cookieVal + “;path=/;expires=” + expDate.toGMTString();     // Creates the cookie


function deleteCookie()


var cookieToDel = document.getElementById(“deleteme”).value;

createCookie(cookieToDel,””,-1);      // Creates a cookie with a name value and expiration in days



<noscript>   <h3>This site requires JavaScript</h3>   </noscript>


<p>Enter Your First Name

<input type=”text” id=”firstname” onblur=”createCookie(‘firstname’);”/><br /></p>

<p>Enter Your Last Name

<input type=”text” id=”lastname” onblur=”createCookie(‘lastname’);”/><br /></p>

<p>Cookie To Delete

<input type=”text” id=”deleteme” onblur=”deleteCookie();”/><br /></p>

<p>Cookie To Get

<input type=”text” id=”getme” onblur=”getACookie();”/><br /></p>

<script type=”text/javascript”>   document.write(“Every Cookie: ” + document.cookie);   </script>



15 Responses to “JavaScript Video Tutorial Pt 9”

  1. Albert Kung says:

    Hi Derek,
    Your video presentations are so lucid and rewarding. Your presentations are the best amount all other presenters because of your celerity, clarity and simplicity . All my Javascript and Jquery understanding is from your teachings. Thank you. Base on your teachings, I wrote a slide show program displaying three images from an Array of three image elements. When the mouse is over the image, the corresponding image should blowup to a bigger size but I cannot do it because I do not know how to pass an index value from FUNCTION to display the corresponding image in . This problem has been hunting me for the last 6 weeks. I do not know what to do except to come to you for help. I studies all your Javascript videos and your jquery video. I still cannot solve my problem, passing index value from LINE#28 i=i+1 to an ARRAY element ”pix[i]” in LINE# 69 . May be just a few comments from you will help me to resolve my frustration. Here is the code for your reference. Thanks and please help!!! If you need me to send you the program and the images, I will be glad to upon your request.

    Albert Kung

    10 #Picture {position: absolute;
    11 top:0px;
    12 border: solid 1px red;
    13 background-color:#FFFF80;
    14 color: purple;
    15 visibility: hidden;
    16 }
    19 slidespeed= 400;
    20 function slideshow(){
    21 showtime=setInterval(“change()”,slidespeed);
    22 }
    23 pix = Array(“img019-06.jpg”,”img018-01.jpg”,”img017-01.jpg”);
    24 i=0;
    25 function change(){
    26 document.images.pic.src=pix[i];
    27 document.getElementById(“count”).innerHTML=i;
    28 i=i+1;
    29 if (i>(pix.length – 1 )) {i=0};
    30 }
    31 function box(boxname,menustate){
    32 if (document.getElementById)
    33 {document.getElementById(boxname).style.visibility = menustate}
    34 else {document[boxname].visibility = menustate}
    35 }

    69 document.write(”)

  2. ron says:

    you are probably aware of this already but i just thought i would let you know that your pages are taking an awful long time to load. I think it could your paypal or something holding it up but its quite frustrating. I am using IE8 .

    thanks .

    • admin says:

      I do my best to keep everything running fast. I can’t afford a dedicated server, but my grid hosted system does a pretty good job most of the time. If you visit the site on days other than Tuesday and Wednesday you shouldn’t have any problems. I’m doing my best 🙂

  3. Greg says:

    Hello again,

    I’ve worked through all your tutorials and am absolutely loving the amount of information that gets packed into such a short time frame.

    This is the first time I’ve had something that didn’t seem to work.

    I checked for typos on my part and then copied and pasted your code directly.

    My problem is that the createCookie function seems to terminate on the getElementById line.

    As I’ve said, I copied and pasted the body section and then the createCookie function. I’ve added some debug lines so that it now reads like this:

    function createCookie(newCookie)

    var expDate = new Date();

    expDate.setMonth(expDate.getMonth() + 1); // Adds 1 month ahead as the expiration date

    var cookieVal = document.getElementById(newCookie).value;

    // Retrieves cookie value from the node that was past to the function

    document.cookie = newCookie + “=” + cookieVal + “;path=/;expires=” + expDate.toGMTString(); // Creates the cookie

    I type “Greg in the firstname field and then tab to the lastname field. The output I get is this:

    It looks like the first three document.write lines are executed and the “var cookieVal = document…” statement doesn’t execute.

    Any ideas on what I’m doing wrong?


  4. marc_nathan says:

    same thing here mr. derek i followed everything you did on this tutorial and again it didn’t is it because of the old browser im using…?

  5. adam says:

    Mr Derek I found that the code just work fine by replacing ″ and ””with “, and ‘ ’with ‘. Thanks For The Tutorial, It is really very nice and easy to understand.

    Adam – Indonesia

  6. leon says:

    Thanks for this video series(enjoyed a lot).I’m done with html,css and javascript….now i have to learn SQL….but i dont know which series to follow.please guide me in this matter.
    and u know what, i dont know a bit of SQL(not even selection of the database and installing it on the system).

    once again thanks a lot for the work which u r doing……..

  7. rego says:

    Hi Derek,

    I have a question regarding the autocorrection in a div tag to set the cursor.
    My Requirement is that I need to auto correct the word in editable div tag. The div tag has able to include the images also. My problem is that I can correct the word once I hit the space after the mispelled word , but the cursor is not setting properly once I included the image.
    Cursor is setting properly when I correct in the middle of sentence or at the end of sentence. Once I included the images, cursor calculation varies.

    Here is the code that is causing the issue.

    //target String = starting string + replaced string
    var targetStr = startStr + rVal;
    if ( document.selection) {
    var myRange = document.selection.createRange();
    myRange.moveToElementText(srcObj); // Here is the issue
    myRange.move(“character”, targetStr.length+1); // move to the corrected string;

  8. shani says:

    derek how document.cookie supposed to get its value from local function

Leave a Reply

Your email address will not be published.