Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery set cookie for first visit

Tags:

jquery

cookies

I got a script like that (I use jQuery cookie js to set cookies) to display layer on first visit.

<script type="text/javascript">
    $(document).ready(function() {
        var visited = $.cookie('visited', 'yes', { expires: 1, path: '/' });

        if (visited == null) {
            $('.newsletter_layer').show();
            $.cookie('visited', 'yes'); 
            alert($.cookie("visited"));         
        }
    });
</script>

Unfortunatelly something is not working. I think something is wrong with the if statement. Anyone have idea what can be wrong?

like image 721
arekk Avatar asked Dec 04 '22 18:12

arekk


1 Answers

Because you are creating the cookie, it will never be null. You need to change your logic to first check if the cookie exists. If not, show the .newsletter_layer element, then set the cookie value:

<script type="text/javascript">
    $(document).ready(function() {
        // check cookie
        var visited = $.cookie("visited")

        if (visited == null) {
            $('.newsletter_layer').show();
            alert($.cookie("visited"));         
        }

        // set cookie
        $.cookie('visited', 'yes', { expires: 1, path: '/' });
    });
</script>
like image 200
Rory McCrossan Avatar answered Jan 03 '23 20:01

Rory McCrossan