0

straight to the point , this is my simple code .

 $(".vm-options a").click( function() {
        $(this).addClass("vmselected").siblings().removeClass("vmselected");
    });

<div class="vm-options">
                <a href="#" class="vm-icon vm-list vmselected" id="list">List view</a>
                <a href="#" class="vm-icon vm-grid" id="grid">Grid view</a>
            </div>

now i need it to remember my choices every time i click on 'a href' tag , how can i add cookie to it .

thank you .

pitfall38
  • 11
  • 1
  • 3
  • You can start from there: [MDN documentation on cookies](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie), or look for [JavaScript cookie libraries](https://www.google.com/search?q=javascript+cookies+plugin), which might be easier and faster to implement. – blex Apr 24 '16 at 20:41
  • thanks for you respond but i'm quite amateur in JS and need to implement cookie in above script as fast as possible , but i thank you to show me how can i start learning about it . – pitfall38 Apr 24 '16 at 20:52
  • 1
    Possible duplicate of [How do I set/unset cookie with jQuery?](http://stackoverflow.com/questions/1458724/how-do-i-set-unset-cookie-with-jquery) – mmgross Apr 25 '16 at 00:08

2 Answers2

0

Use Javascript Cooke plugin and write Cookies.set('name', 'value');

Or the jQuery Cookie plugin and write $.cookie('name', 'value');

Time Rider
  • 29
  • 5
0

This example uses the js-cookie library, which you'll need to include in your page like so:

<script src="https://rawgit.com/js-cookie/js-cookie/master/src/js.cookie.js"></script>

You can use it to store and retrieve the ID of the selected link, this way:

// Select the currently saved VM at page load
selectVM();

// Do it on click too
$(".vm-options a").click(selectVM);

function selectVM()
{
    var elem = $(this);
    // If the call doesn't come from a click (eg on page load),
    // get the one saved in a cookie or the default one: "#list"
    if(this === window) elem = $('#' + (Cookies.get('selectedVM') || 'list'));

    elem.addClass("vmselected").siblings().removeClass("vmselected");
    // Save it for 7 days
    Cookies.set('selectedVM', elem.id, { expires: 7 });
}

Here, the ID is saved in a cookie named selectedVM using:

Cookies.set('selectedVM', value);

and retrieved using:

Cookies.get('selectedVM');

It's that simple!

blex
  • 22,377
  • 5
  • 35
  • 65