Tracking Visitors with Cookies

Free JavaScript & jQuery Tutorial

Improve your understanding of JavaScript and jQuery by learning how to handle cookies, code cookies, clear cookies, update cookies, and submit cookie information with a form in our detailed tutorial, while also gaining insight into tracking visitor information and solving browser-related issues.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Using a JavaScript API for handling cookies, Coding cookies, Clearing cookies, Updating a cookie: incrementing the number of visits, Submitting the cookie info with the form

Exercise Preview

cookies track visitors example

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

Every website should use analytics to track information about their visitors. That anonymous info is useful, but you can take things a step further if you combine forms with JavaScript—to find users’ information such as their landing page, how many times they’ve visited, where they came from, etc.—and store it in a cookie. When that user submits a form, their info is sent along (invisibly to them), offering you more insight into your customers.

Previewing Issues to Keep in Mind

Many browsers do not handle cookies consistently when working with local files. They all support cookies on a live site, and all the techniques shown will work fine on a live site. For security and other reasons, cookies at the local level do not always work as expected. Here are some problems we’ve discovered:

  • Older versions of Safari on the Mac sometimes had issues when a parent folder has a space in the name.
  • Google Chrome and Microsoft Edge do not display local cookies at all.

For the above reasons, we will do all previewing in this exercise with Firefox.

Setting Firefox Preferences

Let’s make sure Firefox is set up to accept cookies. It is by default, but you or someone else on your computer may have changed the preferences and we want to ensure it works properly for this exercise.

  1. Launch Firefox.

  2. Windows users only: Hit Alt to display the menu at the top of the screen.

  3. Go to Firefox > Preferences (Mac) or Tools > Options (Windows).

  4. On the left, click on Privacy & Security.

  5. Under History, next to Firefox will choose Remember history.

  6. Close the window or tab.

Initial Setup Before Moving On

If you are doing this exercise in a classroom (or are doing it for a second time), you must complete the following steps before moving on. If you are doing this exercise at home/work for the first time, you can skip this section.

  1. Launch Firefox.
  2. Hit Cmd–O (Mac) or Ctrl–O (Windows) to open a file.
  3. Navigate to Desktop > Class Files > yourname‑JavaScript jQuery Class and open the Tracking‑Visitors-With-Cookies folder.
  4. Double–click set-up.html to open it.
  5. Click the Clear Cookies button and then click OK. You are done! This has cleared the cookies so you will not be confused by old leftover cookies.

Previewing in Firefox

  1. In Firefox, hit Cmd–O (Mac) or Ctrl–O (Windows) to open a file.

  2. Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class > Tracking-Visitors-With-Cookies. Find enews.html and hit Open.

  3. This is the page where we’ll set some cookies to track user info. Keep this page open in your browser as you work, so you can reload the page to see the changes you make in your code.

Using a JavaScript API for Handling Cookies

A cookie is a small piece of data that is stored in your browser. Cookies are the easiest way to maintain basic user info and are very versatile—they can perform functions such as tracking your visits to websites, enabling you to log in to sites, and storing your shopping cart. Cookies contain the following information:

  • A key-value pair containing the actual data
  • An expiry date after which it is no longer valid
  • The domain and path of the server it should be sent to
  1. Open your code editor if it isn’t already open.

  2. Close any files you may have open.

  3. For this exercise we’ll be working with the Tracking-Visitors-With-Cookies folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to.

    We’ll use js.cookie.js, a simple, lightweight JavaScript API (application programming interface) for reading, writing, and deleting cookies developed by Klaus Hartl and Fagner Brack. You can download it and get the documentation from github.com/js-cookie/js-cookie

    NOTE: This API has no dependencies on other JavaScript libraries, so we’ll keep our setup as lean as possible by using standard JavaScript instead of loading jQuery.

  4. The first order of business is to link to this script. In your code editor, open enews.html from the Tracking-Visitors-With-Cookies folder.

  5. Above the link to main.js (around line 44), add the following bold code:

    <script src="js/vendor/js.cookie.js"></script>
    <script src="js/main.js"></script>
    
  6. Save the file.

  7. Open main.js from the js folder in the Tracking-Visitors-With-Cookies folder.

  8. We want to track how many times a user came to our site before signing up for the newsletter. Create a cookie to store the number of visits by adding this bold code:

    window.onload = function() {
       Cookies.set( 'visits', 1, {expires: 9000} );
    };
    

    NOTE: Cookies.set() is a method defined in js.cookie.js. This line of code creates a cookie named visits. We’ve set it to a value of 1 because it’s their first visit. The cookie will expire in 9000 days. We’d like to store this cookie for a very long time. If you do not specify the optional expiration time, the cookies will expire when the user quits the browser.

  9. Next we’ll create a cookie that saves the page they first enter on. JavaScript can look at the current page’s href (URL) and save it into a cookie. Add the bold code below:

       Cookies.set( 'visits', 1, {expires: 9000} );
       Cookies.set( 'entryPage', document.location.href, {expires: 9000} );
    });
    
  10. Now we’ll create a cookie that saves the date and time of their first visit. For that, we’ll use JavaScript’s built-in Date() object. Add this bold code:

    Cookies.set( 'visits', 1, {expires: 9000} );
    Cookies.set( 'entryPage', document.location.href, {expires: 9000} );
    Cookies.set( 'entryDateTime', Date(), {expires: 9000} );
    

    NOTE: The time will be in 24 hour (military) time with the time zone. The Date() object can be reformatted to AM/PM, etc., but the default formatting will suit our needs just fine.

  11. Lastly we want to find out the webpage that sent them to the site. JavaScript can get the referring page’s href (URL) and save it into a cookie. Add this bold code:

    Cookies.set( 'visits', 1, {expires: 9000} );
    Cookies.set( 'entryPage', document.location.href, {expires: 9000} );
    Cookies.set( 'entryDateTime', Date(), {expires: 9000} );
    Cookies.set( 'cameFrom', document.referrer, {expires: 9000} );
    

    NOTE: document.referrer is the URL of the page the user came from. This will be blank if they directly typed in the URL for the page/site.

  12. Save the file.

  13. Reload enews.html in Firefox. As we mentioned earlier in this exercise, other browsers may have problems with local cookies, so be sure to use Firefox.

  14. In Firefox, don’t fill out the form, just click Sign Me Up! to submit it.

  15. On the Thanks for Signing Up page that appears, check out the values for:
    • Number of Times Visited
    • Entry Page
    • Entry Date/Time

    NOTE: Came From will be blank because we are testing locally. You’ll have to trust us that it works. We will make the Currently Here cookie work later.

  16. Find the time part of Entry Date/Time and make a note of the time.

  17. Click the Go Back to Form link (to the right of the Clear Cookies button).

  18. Click Sign Me Up! to submit the form again.

  19. Notice that the time changes. Currently, all these cookies are being set every time the user visits the page, but they should only be set on their first visit. Let’s fix this.

  20. Switch back to main.js in your code editor.

  21. We need to check to see if the visits cookie has been created yet. We can use Cookies.get() to do so. If it hasn’t, then it is a user’s first visit and we should create the cookies. Otherwise, nothing should happen. Add the following bold code:

    window.onload = function() {
       var v = Cookies.get('visits');
       if ( v == undefined ) {
          Cookies.set( 'visits', 1, {expires: 9000} );
          Cookies.set( 'entryPage', document.location.href, {expires: 9000} );
          Cookies.set( 'entryDateTime', Date(), {expires: 9000} );
          Cookies.set( 'cameFrom', document.referrer, {expires: 9000} );
       }
    };
    

    NOTE: We’re using v as a variable name because it’s short for visits. We already have a visits cookie, so we didn’t want to use that as a variable name again.

  22. Save the file.

  23. Switch to Firefox and reload enews.html.

  24. Click Sign Me Up! to submit the form.

    Notice that the entry time is still an older time from when you previewed earlier. Hmm. We need to reset our cookies in order to see if the code we wrote is working.

Clearing Cookies

  1. Switch back to your code editor.

  2. Open thank-you.html from the Tracking-Visitors-With-Cookies folder.

  3. Let’s write some code that will clear out our cookies when we click the Clear Cookies button that’s on this page. Around line 66, add the following bold code to watch for when our button is clicked:

          // Clear Cookies
          document.getElementById('clearCookies').onclick = function() {
    
          };
    
       };
    </script>
    
  4. Next, add the following bold code to clear out our cookies:

    // Clear Cookies
    document.getElementById('clearCookies').onclick = function() {
       Cookies.remove('visits');
       Cookies.remove('entryPage');
       Cookies.remove('entryDateTime');
       Cookies.remove('cameFrom');
       Cookies.remove('currentlyHere');
    };
    
  5. To make sure our code works, let’s get the value of our cookies and write them to the Console so we can see that they’ve been cleared. Add the following bold code:

    document.getElementById('clearCookies').onclick = function() {
       Cookies.remove('visits');
       Cookies.remove('entryPage');
       Cookies.remove('entryDateTime');
       Cookies.remove('cameFrom');
       Cookies.remove('currentlyHere');
    
       console.log( 
          Cookies.get('visits'),
          Cookies.get('entryPage'),
          Cookies.get('entryDateTime'),
          Cookies.get('cameFrom'),
          Cookies.get('currentlyHere') 
       );
    };
    
  6. Save the file.

  7. Switch to Firefox and reload enews.html.

  8. Click Sign Me Up! to submit the form.

  9. Before we clear the cookies, let’s open up the Console to make sure it works. Ctrl–click (Mac) or Right–click (Windows) on the page and select Inspect Element to bring up the Web Developer Tools.

  10. Click the Console tab at the top of the Web Developer Tools.

  11. Click the Clear Cookies button on the page.

  12. In the Console, you should see undefined 5 times, once for each cookie. This means our cookies have been successfully cleared.

  13. Close the Web Developer Tools.

  14. Click the Go Back to Form link (to the right of the Clear Cookies button).

  15. Click Sign Me Up! to resubmit the form.

    The date should now be just a few seconds old, indicating that the cookies are properly set again.

  16. Click the Go Back to Form link and then Sign Me Up! to submit the form again. Notice that the time does not change. Perfect!

Updating a Cookie: Incrementing the Number of Visits

  1. The visits cookie is currently stuck at 1, but it should increment every time the user visits the site. We can increment the value of v and then re-save the cookie using the updated value. Return to your code editor.

  2. Switch to main.js.

  3. Add the following bold code:

    window.onload = function() {
       var v = Cookies.get('visits');
       if ( v == undefined ) {
    

    Code Omitted To Save Space

       }
       else {
          v++;
          Cookies.set( 'visits', v, {expires: 9000} );
       }
    };
    

    NOTE: v++ says to take the value of v and increment it by 1. Then we set the cookie equal to that new value.

  4. Save the file.

  5. Return to thank-you.html in Firefox and click the Go Back to Form link.

  6. Click Sign Me Up! to submit the form again.

  7. Go back and submit the form several times and watch the Number of Times Visited increase. (Nothing else should change, just the number of visits.)

    The visits cookie should increase every time the user visits the site—but not every time they load a page! We want the visits to increase once per session. (A session ends when the user quits the browser.) This will give a more accurate number of how many times the user has visited your site over time.

  8. Return to main.js in your code editor.

  9. To fix this we will create a cookie called currentlyHere. We’ll use that to see whether the user is on the site. By not specifying an expiration, it will expire at the end of the session. Add the following bold code:

       else {
          v++;
          Cookies.set( 'visits', v, {expires: 9000} );
       }
       Cookies.set( 'currentlyHere', 'true' );
    };
    
  10. Now let’s check to see if the currentlyHere cookie exists. If it does not (meaning they have not previously visited the site in this session), we will increase the number of visits. Add the following bold code (there are two places you need to add code):

    window.onload = function() {
       var v = Cookies.get('visits');
       var c = Cookies.get('currentlyHere');
       if ( v == undefined ) {
    

    Code Omitted To Save Space

       }
       else if ( c == undefined ) {
          v++;
          Cookies.set( 'visits', v, {expires: 9000} );
       }
       Cookies.set( 'currentlyHere', 'true' );
    };
    
  11. Save the file.

  12. Return to thank-you.html in Firefox.

  13. Click the Go Back to Form link and then Sign Me Up! to submit the form again and:

    • Resubmit the form a few times. Notice that the Number of Times Visited does not increase.
    • Stop submitting the form and, on thank-you.html, take note of the current Number of Times Visited. (You will want to make sure it increases by one in a moment.)
    • Quit Firefox.
    • Preview enews.html in Firefox and submit the form again.
    • Notice the Number of Times Visited should be one number higher than it was before you quit. This proves our session cookie is working!

Submitting the Cookie Info with the Form

Our cookies are working, but when a signup form is submitted, it does NOT submit any of the cookie data to the web server. This means the cookie data is only stored on the user’s machine and the website owner would never know what it is. We can fix that by creating hidden field inputs in our form. We can then use JavaScript to set the values of those hidden inputs. The values of those hidden inputs can be submitted (along with the rest of the form inputs) so the website owner can see this useful info. Sneaky, huh?

  1. Switch back to your code editor.

  2. Switch to enews.html.

  3. We need to create an input for each cookie we want to submit along with the form. To save you some typing, we’ve coded up the HTML. From the snippets folder, open hidden-inputs.html.

  4. Select and copy all the code.

  5. Switch back to enews.html.

  6. Around line 35, find the code for the Sign Me Up! submit button.

  7. Below that button, paste the code so you end up with the following:

    <input id="submit" type="submit" name="submit" value="Sign Me Up!">
    
    <input type="text" name="visits" id="visits">
    <input type="text" name="entryPage" id="entryPage">
    <input type="text" name="entryDateTime" id="entryDateTime">
    <input type="text" name="cameFrom" id="cameFrom">
    

    NOTE: Notice these are text inputs, not hidden inputs. As we code we want them to be visible, so we can see their values. When we’re done testing, we’ll change their type to hidden.

  8. We need to set the values of these text fields equal to the contents of our cookies. We could add this code to main.js, but it’s unique to this page. Let’s embed it to keep things simple. Add the following bold code before the closing </body> tag:

       <script src="js/main.js"></script>
       <script>
          window.onload = function() {
    
          };
       </script>
    </body>
    </html>
    
  9. First let’s get the value of the visits input. Add the following bold code:

    <script>
       window.onload = function() {
          document.getElementById('visits').value;
       };
    </script>
    
  10. Now we can set it to the value of the visits cookie. Add the following bold code:

    window.onload = function() {
       document.getElementById('visits').value = Cookies.get('visits');
    };
    
  11. We have three other inputs/cookies, so copy and paste that line of code so you end up with a total of 4 lines as shown below.

    window.onload = function() {
       document.getElementById('visits').value = Cookies.get('visits');
       document.getElementById('visits').value = Cookies.get('visits');
       document.getElementById('visits').value = Cookies.get('visits');
       document.getElementById('visits').value = Cookies.get('visits');
    };
    
  12. We just have to change the names of the form fields and cookies. Make the changes shown in bold:

    window.onload = function() {
       document.getElementById('visits').value = Cookies.get('visits');
       document.getElementById('entryPage').value = Cookies.get('entryPage');
       document.getElementById('entryDateTime').value = Cookies.get('entryDateTime');
       document.getElementById('cameFrom').value = Cookies.get('cameFrom');
    };
    
  13. Save the file.

  14. Switch to Firefox, reload enews.html, and:

    • Below the Sign Me Up! button notice there are some new text fields. These are the ones we just added.
    • The first field should have a number in it. That’s the number of visits.
    • The next field should have a URL. That’s the entry page.
    • The next field should be the date and time.
    • The last field is empty because there was no referring page, but this would work on a live site.
  15. Now that we know they are working, we can change the type from text to hidden so the user doesn’t see these. Return to enews.html in your code editor.

  16. Find the input tags starting around line 37 and change the type from text to hidden. TIP: In Visual Studio Code you can select the first copy of text. Then hit Cmd–D (Mac) or Ctrl–D (Windows) a few times to select the other copies. Once all four are selected, type hidden to update them all at once!

    <input type="hidden" name="visits" id="visits">
    <input type="hidden" name="entryPage" id="entryPage">
    <input type="hidden" name="entryDateTime" id="entryDateTime">
    <input type="hidden" name="cameFrom" id="cameFrom">
    
  17. Save the file.

  18. Switch to Firefox and reload enews.html to see that the fields are hidden. Don’t worry though, they still work when hidden!

    That’s all we have to do for the front-end. You may need to adjust your server-side script that processes the form, so it will include the info from these hidden inputs. The info is there for the taking, though! We hope this lets you gain powerful insights into your web visitors and customers.

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Tracking-Visitors-With-Cookies.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram