Question

I am looking to have 3 different divs displayed 1 div on the 1st visit 2nd div on the 2nd visit 3rd div on the 3rd visit

I thought I had the code to make this happen but it is not working and I am having trouble figuring out what I'm doing wrong.

$(document).ready(function() { 

    var cookieRCCS = $.cookie('shownDialog');

    console.log(cookieRCCS);

     // Check if the cookie exists.
    if ( cookieRCCS === null ) {
        console.log("1st if statement " + cookieRCCS);
        $("#hellopanel1").show();

        // set the cookie to value 1
        $.cookie('shownDialog', '1', {expires: 7});

    } 
    else if ( cookieRCCS === 1 ) {
        console.log("2nd if statement " + cookieRCCS);      
        $("#hellopanel2").show();

        // If the cookie exists, take the value
        cookie_value = $.cookie('shownDialog');

        // Convert the value to an int to make sure
        cookie_value = parseInt(cookie_value);

        // Add 1 to the cookie_value
        cookie_value++;

         // Save the incremented value to the cookie
        $.cookie('shownDialog', cookie_value, {expires: 7});

    }
    else if ( cookieRCCS === 2){
        console.log("3rd if statement " + cookieRCCS);

        $("#hellopanel3").show();

        cookie_value = $.cookie('shownDialog');

        cookie_value = parseInt(cookie_value);

        cookie_value++;

        $.cookie('shownDialog', cookie_value, {expires: 7});
    }

    else{
        console.log("4th Time Here");
    }

});
Was it helpful?

Solution

This will solve your problem witha simple and elegant case statement to properly trigger the pieces of code in a cascading fashion:

$(document).ready(function() { 
    var cookieRCCS = (+$.cookie('shownDialog')) + 1;
    $.cookie('shownDialog', cookieRCCS,{expires: 7});

    console.log(cookieRCCS);

    switch (cookieRCCS) {
        case 1:
            console.log("1st if statement " + cookieRCCS);
            $("#hellopanel1").show();
            break;

        case 2:
            console.log("2nd if statement " + cookieRCCS);      
            $("#hellopanel2").show();
            break;

        case 3:
            console.log("3rd if statement " + cookieRCCS);
            $("#hellopanel3").show();
            break;

        default:
            console.log("4th+ Time Here");
    }
});

OTHER TIPS

Because you're writing a string to the cookie, but checking type with ===. Just change your if comparison to == or do var cookieRCCS = +$.cookie('shownDialog'); which will convert it to a number (which means you have to check if cookieRCCS == 0 instead of null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top