Skip to content

Instantly share code, notes, and snippets.

@waldoj
Created May 14, 2011 18:55
Show Gist options
  • Save waldoj/972502 to your computer and use it in GitHub Desktop.
Save waldoj/972502 to your computer and use it in GitHub Desktop.
An effort to create a simple session array manipulation function in JavaScript.
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<script src="https://www.google.com/jsapi?key=ABQIAAAAn01L8sl4uwWn5vTPpoEoXhQlhX9aoLwtuBlP8SLx1ePnrLY9UBT9g3_4EQBp1uyDz1sgvvv7UqG-nQ"></script>
<script>
google.load("jquery", "1.4.3");
</script>
<script src="http://socorro.googlecode.com/svn/trunk/webapp-php/js/jquery/plugins/jquery.cookies.2.2.0.js"></script>
</head>
<div id="portfolio-toggle">Add to Portfolio</div>
<script>
// Imagine that this script is included on section 3.2-601 of the state code. This variable
// would be defined within that page, and passed to this JavaScript. Instead, of course, we're
// defining it manually here.
var section = '3.2-601';
// Define the ID of the portfolio toggle button.
var button = $('#portfolio-toggle');
// Store the value of the cookie in a local array.
var portfolio = $.cookies.get('portfolio');
portfolio = jQuery.parseJSON(portfolio);
// If, on page load, the current section is stored in the portfolio cookie, then indicate that
// by toggling the display on. Since the first position in an array is position 0, position -1
// is how this returns false.
if (jQuery.inArray(section, portfolio) !== -1)
{
togglePortfolio(button, true);
}
// Handle the clicking of the add/delete toggle.
button.click(function() {
// Toggle the portfolio state. If it's currently in the "on" state, then this click means
// it should be turned off.
if (button.hasClass('in-portfolio') === true) {
togglePortfolio($(this), false);
}
// Otherwise, it should be turned on.
else {
togglePortfolio($(this), true);
}
});
// Modify the cookie data and modify the DOM.
function togglePortfolio(button, store) {
// If we're adding a new law to the portfolio, add the appropriate class to it and and add
// it to our array.
if (store) {
// Add the style to the element.
button.addClass('in-portfolio');
// Add this section to the portfolio array.
portfolio.push(section);
}
// If we're deleting a law from the portfolio, delete it from our array and eliminate the
// class.
else {
// Remove the style from the page.
button.removeClass('in-portfolio');
// And drop the item from the portfolio array.
portfolio = jQuery.parseJSON(portfolio);
position = jQuery.inArray(section, portfolio);
if (position > -1) {
// I have no idea of why this is necessary.
position = position - 1;
portfolio = portfolio.splice(position,1);
}
}
// Put the new portfolio array into the cookie.
portfolio = JSON.stringify(portfolio)
$.cookies.set('portfolio', portfolio);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment