Search code examples
jqueryfancybox

Setting cookie on click fancybox close button


I know about jquery cookie plugin .But I am stuck to set cookie on click close button. Here is my approach.

 <script type='text/javascript' src='jquery-latest.js'></script>
 <script type='text/javascript' src="jquery.fancybox.js"></script>
 <link rel="stylesheet" type="text/css" href="jquery.fancybox.css">
 <script src="jquery.cookie.js"></script>

then for cookie and fancybox

$(".fancybox-close").on("click", function () {
    $.cookie('the_cookie', 'the_value', { expires: 7 });
});
jQuery(function() {
    jQuery.fancybox(jQuery(".popup"), {
        // other API options
    }); 
});

The html code

  <div class="popup" style="display: none;">
    <h1>Hi there </h1>
  </div>

I see that if I do

$.cookie('the_cookie', 'the_value', { expires: 7 });

this set cookie but I want to set on click close button.


Solution

  • Try below:

    jQuery(function() {
        $.fancybox($(".popup"), {
            // other API options
        });
    
        // put your code inside dom ready callback too.
        // and delegate the click event on document
        $(document).on('click', '.fancybox-close', function () {
            $.cookie('the_cookie', 'the_value', { expires: 7 });
        });
    });