javascriptjqueryhtmljquery-cookie

Not to show popup once closed in jQuery using cookies


I am using the below code for not to show a popup once closed. I tried the below code but it's not working. I checked on google but haven't found the solution.

Would you help me out with the solution?

$(document).ready(function() {
  $('.closeme').click(function() {
    $('#popup').hide();
    if ($.cookie('whenToShowDialog') == null) {
      // Create expiring cookie, 2 days from now:
      $.cookie('whenToShowDialog', 'yes', {
        expires: 2,
        path: '/'
      });
      // Show dialog
      $('#popup').show();
    }

  });
});
#popup {
  background-color: #f8f8f8;
  padding: 20px;
  width: 400px;
  position: relative;
}

#popup h2 {
  font-size: 25px;
}

.closeme {
  position: absolute;
  top: 10px;
  right: 15px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/js/all.min.js"></script>
<div id="popup">
  <div class="closeme"><i class="far fa-window-close"></i></div>
  <h2>Test popup</h2>

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>


Solution

  • Yes, Finally I fount the solution, I set display: none to the#popup in the CSS.

    First, it will check the cookies are really available or not. If not then it will display the popup and once you close the popup it will set the cookies for one day.

    $(document).ready(function() {
      if ($.cookie('whenToShowDialog') != "true") {
        $("#popup").show();
        $(".closeme").click(function() {
          $("#popup").hide();
          // set the cookie for 24 hours
          var date = new Date();
          date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
          $.cookie('whenToShowDialog', "true", {
            expires: date
          });
        });
      }
    });
    #popup {
      background-color: #f8f8f8;
      padding: 20px;
      width: 400px;
      position: relative;
      display: none;
    }
    
    #popup h2 {
      font-size: 25px;
    }
    
    .closeme {
      position: absolute;
      top: 10px;
      right: 15px;
      cursor: pointer;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/js/all.min.js"></script>
    <div id="popup">
      <div class="closeme"><i class="far fa-window-close"></i></div>
      <h2>Test popup</h2>
    
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>