Categories
Javascript

Simulating FIFO with Javascript

Recently I needed to create a little workaround to get our product compare feature to work across multiple pages. Here’s what I needed:

  • Uses session cookies for list management
  • Maximum of 10 products
  • Auto-check boxes across multiple pages if the cookie values match product skus
  • Submit the cookie to another page and rebuild the querystring.


First, the cookie management was easily handled by some code I picked up from http://www.quirksmode.org (great website, btw). The little code there just accepts some values for cookie duration, and a name and takes care of all the date manipulation.

The second obstacle was simulating a FIFO stack (First In, First Out). For example, the user selects 10 products (10 to 1). When the 11th product is selected, the first product has to be removed (making it 11 to 2). This was accomplished using the unshift() and pop() functions. I simply read the cookie in, unshift() the new value into the array, then, if the list is greater than 10, pop() off the last value.

Third, the auto-checking of products that match items in the cookie array. This was a bit more difficult, and the only solution I could come up with was less than optimal. The codebase we’re working from doesn’t allow us to easily access the <body> tag and the javascript for this is in an external file called at the top of the page, so the onLoad() event wouldn’t work in the body or in the script tag. After some research, I found that onLoad() works with <img> tags, so I used this at the bottom of the page. This, unfortunately, causes just a tiny bit of lag after the page loads but before the boxes are checked.

The final piece was pretty simple by using a javascript window.location to redirect the page on submit and build the proper querystring.

Yes, I know it’s ugly, but it works!