Tuesday, April 22, 2014

jQuery Cookie - How to make a CSS change persist between page requests.

jQuery Cookie and Changing CSS between page requests.

I was recently working on a jQuery function to show the third column of a table. My difficulty existing in persisting this state change between user requests. Here is my method using.

 https://github.com/carhartl/jquery-cookie

SASS
.table { td:nth-child(3){ text-align: right; width: 90px; visibility: hidden; } }
.make_visible { visibility: visible !important; }
JavaScript
$('.howAmIDoing').on('click', function() { $('.table td:nth-child(3)').toggleClass("make_visible"); if ($.cookie('compare-medium') == 'true'){ $.removeCookie('compare-medium'); } else { $.cookie('compare-medium', 'true') } }); if($.cookie('compare-medium') == 'true'){ $('.table td:nth-child(3)').addClass("make_visible"); };
What is Happening?
1. By default every third column on the table's visibility is set to hidden.
2. On click I use the jQuery toggleClass method to add a CSS class with a higher specificity to make the third column visible.
3. When this is occurs, I write to the cookie.
4. On page load if that cookie exists add the class.
5. If the button is clicked again, I remove the css class


No comments:

Post a Comment