onestepcreative
onestepcreative

Reputation: 561

Store a list of data id's in a cookie with jQuery

I'm trying to create a list of data-id's and store them in a cookie, so I can loop thru them later and manipulate them as needed. This needs to be done client-side, so I'm wanting to use jQuery Cookies.

Say I have a list of portfolio items with a unique data-id attribute associated with each item. When a user clicks into a single portfolio item, I need to store that specific data-id into a jQuery cookie, so I can reference it later.

What is the best way of going about this?

Upvotes: 1

Views: 1261

Answers (2)

Phil.Wheeler
Phil.Wheeler

Reputation: 16848

Edited

So you want to check which portfolio pages a user has already visited (NB: instead of cookies, you might also consider the HTML5 History API or localStorage).

When a user visits a page, you want to retrieve the portfolio ID from somewhere. That might be within a DOM element or it could be in the query string of the URL. I'm going to assume it's the latter.

// Get the portfolio ID from the query string
var currentId = new RegExp("[\\?&]MYID=([^&#]*)").exec(location.search)[1]
// Replace MYID in the line above with the name of your querystring parameter

Ok, so we have our Id. Next we need to read any existing ones from our cookie. If the cookie doesn't exist we need to create it.

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

if (get_cookie('readPortfolios') == null) {
  // Extremely simplified implementation
  document.cookie = 'readPortfolios=' + currentId;
}
else {
  // We have a cookie already. We'll read it
  var ck = get_cookie('readPortfolios');

  // We want to add this page's portfolio Id
  ck += ',' + currentId;

  // We then want to save the cookie back
  document.cookie = 'readPortfolios=' + ck;
}

So that's our per-page stuff complete. Next we want to look through our list on the main page to see which pages have been visited.

Assuming you have a list that looks like the following:

<ul id="myPortfolioList">
  <li id="data-id-1">Text One</li>
  <li id="data-id-2">Text Two</li>
  <li id="data-id-3">Text Three</li>
</ul>

First I need my cookie values, then I want to compare these to the Id values of my list items.

var values = get_cookie('readPortfolios').split(',')

$('#myPortfolioList li').each(function(){
  if ($.inArray(this.id, values) > -1) {
    console.info('Portfolio Item ' + this.id + ' has been visited.');
  }
});

Upvotes: 1

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

You could JSON Stringify the array and then store it in the cookie.

Upvotes: 2

Related Questions