Monday, May 13, 2013

Using jQuery Cookie to store state of an element

This is just an amazing jQuery plugin to manipulate cookies:

The plugin is so awesome because it helped me to get rid of the complicated and repeated line of code I use to return to the template to render state of an element, (e.g the current selected menu item). I was use something stupid like:

def my_view(request):
      selected_nav = 'First menu'

my_template.html: I then get the return value and choose which menu is in the selected state:


<script type="text/javascript">
console.log("{{ selected_nav }}");
jQuery("#nav a").each(function(){ jQuery(this).removeClass("selected"); });
jQuery("#nav a:contains('{{ selected_nav }}')").addClass("selected");


I thought about session and cookie, It was really annoying when have to write to the session the value I want whenever I define a view. My code was a mess.

Today, I found the jQuery Cookie. I feel so good because all of those thins above I can do at the client side from now on, with jQuery Cookie. It's just as easy as following:

- Create a cookie:

jQuery.cookie('cookie_name', 'cookie_value');

- Read a cookie :