2

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.

1 Answer 1

7

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');
}
Sign up to request clarification or add additional context in comments.

4 Comments

Very thanks for your code, is very useful. Btw, I'm newbie in jQuery and I'm doing something wrong. this is my code: pastebin.com/f3F0mrKP The console output is: "Uncaught SyntaxError: Unexpected end of input (anonymous function)" If I could explain why I'm so stupid I'd appreciate it.
@KikoBeats You're welcome! Can you put your code into a fiddle on jsfiddle.com? It would be easier to see what's happening then.
nice idea! This is my code without cookie in js file: jsfiddle.net/Kikobeats/xNUCF/11.
OK, mi problem is with 'elements = JSON.parse($.cookie('elements'));' return undefinied. How I can fix it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.