View Full Version : Passing js function inside cookie js function

09-30-2012, 10:34 PM
What is the proper syntax to pass a js function from one .js file inside the function of another .js file?

So the two .js files are simpleCart.js and cartCookie.js (simpleCart is huge, I'm sure some of you are familiar with it, the only function i'm using in this case is simpleCart_items)

Here's what I do on my item.html page, using createCookie from cartCookie.js:

<span class = 'createCookie("cart","simpleCart_items",1)'></span>

"simpleCart_items" should return all the items in the cart, in string format.

And then users can click their cart, which brings them to checkout.html. To access the items in checkout.html, I use readCookie from cartCookie.js:

<span class = 'readCookie("cart")'></span>

Here's cartCookie:

function createCookie(name,value,days) {
if (days) {
var date = new Date();
var expires = "; expires="+date.toGMTString();
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
return null;

function eraseCookie(name) {

I feel like this is a simple problem to fix, I just don't know enough about javascript syntax :mad:

Old Pedant
09-30-2012, 11:41 PM
Ummm...none of that makes much sense.

(1) These are both nonsense:
<span class = 'createCookie("cart","simpleCart_items",1)'></span>
<span class = 'readCookie("cart")'></span>
All you have done is set the className of each of those <span>s to a weird string of characters. You certainly have not invoked any JavaScript code, whatsoever.

(2) Even if you somehow managed to invoke JavaScript code, this makes no sense at all:
All you have done there is passed in a STRING and asked to store that string in the cookie.

So, later when you read the cookie, all you are going to get OUT of the cookie is a string: "simpleCart_items" You most certainly are NOT going to get the contents of any object; that is, you certainly aren't going to get any shopping cart.


In all of this, I don't see how the topic of this thread is addressed, at all.

I don't see any place where you are even attempting to store a JavaScript function in a cookie.


FWIW, if you wanted to store all the items in your simpleCart in a cookie, you would need to do something like this:

<script type="text/JavaScript">

Notice this has nothing to do with a <span>. Notice that you do *NOT* put quotes around the name of the object you want to store. And notice, finally, that this code only works if the object simpleCart_items indeed has a toString() method that will "serialize" the object into a string, since you can't really store object in cookies, at all.