2

I would like to know how do I detect multiple cookies. I have two button with class- .attack_enabled and .restore_enabled, both create cookie called attackcompletecookie and restorecompletecookie, respectively.

How do I detect both cookies and add a class to .territory_middle_complete

Here's my code:

$(".attack_enabled").click(function(){

   createCookie('attackcompletecookie','attack_cookie');

});

$(".restore_enabled").click(function(){

   createCookie('attackcompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');

});

if(atkcomplete){
   console.log(atkcomplete);
   $(".territory_middle_complete").addClass("displayblockzindex2");
}
Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
Joe
  • 112
  • 5

1 Answers1

0

Try to use id instead class to refer in jQuery, leave the classes for CSS.

Check it here http://jsfiddle.net/hbzqnrm8/5/

I hope it helps you.

<button id="attack_enabled">ATTACK</button>
<button id="restore_enabled">RESTORE</button>

<div class="territory_middle_complete">ADD A CLASS HERE</div>

I've edited your jQuery code, and add what I think you want to achieve. Of course if you want to check the existance of the cookie when clicking the "restore" button, if not, just move the if condition wherever you needed, but not outside the click function, because it will be executed only on loading the file.

$("#attack_enabled").click(function(){
   createCookie('attackcompletecookie','attack_cookie');
});

$("#restore_enabled").click(function(){
   createCookie('restorecompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');
   if(atkcomplete)
   {
       alert(atkcomplete);
       $(".territory_middle_complete").addClass("displayblockzindex2");
    }
});

function createCookie(cookieName, cookieId) {
    document.cookie = cookieName + '=' + cookieId;
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}
Adrian Bolonio
  • 517
  • 4
  • 17
  • So, if that helps you, please mark the answer as correct and give +1 to the answer. I'm glad it helped you :) – Adrian Bolonio Feb 06 '15 at 14:23
  • I'm a new user here, cant help to +1 to the answer. sorry. I have another question. How do I set an expiration date of the cookies to the answer above? – Joe Feb 06 '15 at 14:29
  • Check this answer http://stackoverflow.com/a/1460174/1181310, you can copy the functions createCookie and readCookie from there. Just add days as parameter on the function. – Adrian Bolonio Feb 06 '15 at 15:33