Simon Kiely
Simon Kiely

Reputation: 6050

Javascript code for creating cookie

I am trying to make a popup appear on a webpage only once, using Javascript.

So on page load, I create a cookie. Then I have an if statement - if the cookie has already been made, I don't wish to display the popup - so I am fading it out. (Is there a better way to just make this not appear at all?)

I have created a codebox here.

JS here, both areas it is targetting are simple divs :

$(document).ready(function(){
    var visited = $.cookie('visited'); // create the cookie
    if (visited == 'yes') {
       $("#popup").fadeOut();
       $("#popup").fadeOut();
    } 
    else 
    {
    $("#hover").click(function(){
           $(this).fadeOut();
       $("#popup").fadeOut();
      });
    $("#close").click(function(){
           $("#hover").fadeOut();
       $("#popup").fadeOut();
    });
    $.cookie('visited', 'yes', {
        expires: 7 // the number of days the cookie will be effective
    });                    
    }
  });

Unfortunately, none of the Javascripts seems to run - the popup will no longer close or recognize clicks and displays every time the user navigates to the page.

What have I done incorrectly here and how can I fix it ?

Upvotes: 0

Views: 83

Answers (1)

Sushant Khurana
Sushant Khurana

Reputation: 91

I used the code below to display a webpage only once and ask the visitor to submit their details. If the details are submitted once, from next time the page redirects to another page.

<script>

        go_to = "kwd.php";

        num_days = 180;
        function ged(noDays){
            var today = new Date();
            var expr = new Date(today.getTime() + noDays*24*60*60*1000);
            return  expr.toGMTString();
        }

        function readCookie(cookieName){
            var start = document.cookie.indexOf(cookieName);
            if (start != -1){ 
            window.location = go_to;
            }
        }

        function createcookie() {
            document.cookie = "seenit=yes; expires=" + ged(num_days);
        }

        readCookie("seenit");
</script>

Upvotes: 1

Related Questions