How do I run this JavaScript function and HTML only if a specific cookie does not exist

I created the JavaScript below and HTML snippet below to show a slide-in style of popup on a webpage. If the user closes the popup, it also creates a cookie (cmmctageneral) with a value of "yes".

I'd like to now check if the cookie exists and only run the code if it does not. So that the end result is if the user closes the slide-in, it will not appear until the cookie expiration.

So basically I want to:

Check cookie; If cookie doesn't exist then run the code If cookie does exist then stop

Here's the code:

<script type="text/javascript">
jQuery(document).ready(function($) {
  var slidebox = $('#slidebox');
  if (slidebox) {
$(window).scroll(function(){
    var distanceTop = $(document).height()*0.3;
    if  ($(window).scrollTop() > distanceTop)
        slidebox.animate({'right':'0px'},300);
    else
        slidebox.stop(true).animate({'right':'-430px'},100);
});
$('#slidebox .close').on('click',function(){
    $(this).parent().remove();
    var d = new Date();
    d.setTime(d.getTime() + (30*24*60*60*1000));
    document.cookie = "cmmctageneral=yes; expires=" + d.toUTCString() + "; path=/";
});
 }
});
</script>
<div id="slidebox"><a class="close">&nbsp;</a><a href="https://www.example.com/" target="_blank"><img class="shadow alignCenter" style="width: 100%; height: auto;" src="https://www.example.com/wp-content/uploads/slide-out-cta-template.jpg"></a></div>

Thanks for the help

Answers 1

  • You can do something like this:

    jQuery(document).ready(function($) {
      var slidebox = $('#slidebox');
      //check if cookie exists
     if(document.cookie.indexOf('cmmctageneral=')>-1){      
        //remove slider
        slidebox.remove();
      }else if (slidebox.length>0) {
        $(window).scroll(function(){
            var distanceTop = $(document).height()*0.3;
            if  ($(window).scrollTop() > distanceTop)
                slidebox.animate({'right':'0px'},300);
            else
                slidebox.stop(true).animate({'right':'-430px'},100);
        });
        $('#slidebox .close').on('click',function(){
            $(this).parent().remove();
            var d = new Date();
            d.setTime(d.getTime() + (30*24*60*60*1000));
            document.cookie = "cmmctageneral=yes; expires=" + d.toUTCString() + "; path=/";
        });
       }      
    });
    

Related Articles