Jquery Cookie onclick function

15,365

Take a look at the jQuery Cookie plugin. It makes working with cookies very simple.

Creating the cookie is as simple as:

$.cookie('the_cookie', 'the_value');

If you want to store the elements in the cookie, it will require a little more work. If your element's id's are static, then you can store them in an array and then store that to the cookie by using JSON.stringify:

var elements = [];
$(".colabs-image").click(function() {
    $(this).parent().addClass('is-visited');
    elements.push($(this).parent().attr('id')); //add the id to the array of elements
    $.cookie('elements', JSON.stringify(elements));
});

To retrieve the elements, you will have to use JSON.parse:

var elements = JSON.parse($.cookie('elements'));
for(var i = 0; i < elements.length; i++) {
    $("#" + elements[i]).addClass('is-visited');
}
Share:
15,365
Kiko Beats
Author by

Kiko Beats

Updated on June 04, 2022

Comments

  • Kiko Beats
    Kiko Beats almost 2 years

    I have this function in jQuery for hide elements when the user click in them:

      $(".colabs-image").click(function() {
        $( this ).parent().addClass('is-visited');
      });
    

    I want to use a cookie to store the elements in which the user has clicked and display as visited next time.

    Whit $(this).parent().attr('href')) I have a ID for the element, but I know how to manage the cookie for this task.