简体   繁体   中英

Set cookie to only show DIV once per session

I have a DIV which is displayed on page load. It can be closed via a button or by clicking anywhere in the window (as per a regular modal).

I need this DIV to only be shown once per session. At the moment it is shown every time a new page loads on the site. Is there an easy solution?

I'd like to continue using JQuery show/hide to do this as per my working version below. Any help greatly appreciated.

HTML

<div id="promoModal" class="promomodal">
  <div class="promo-modal-content">
    <span class="promo-close">&times;</span>
    CONTENT
  </div>

</div>

CSS

  .promomodal {
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.7);
    padding: 10px;
  }

  .promo-modal-content {
    background-color: #071177;
    margin: 15% auto;
    padding: 10px;
    max-width: 500px;
    text-align: center;
  }

  .promo-close {
    color: #fff;
    float: right;
    top: 0;
    font-size: 28px;
    font-weight: bold;
  }

</style>

JS

var modal = document.getElementById("promoModal");
var span = document.getElementsByClassName("promo-close")[0];

  jQuery(document).ready(function ($) {

    $('.promomodal').show();

    span.onclick = function () {
      jQuery('.promomodal').hide();
    }
    window.onclick = function (event) {
      if (event.target == modal) {
        jQuery('.promomodal').hide();
      }
    }
  });

</script>
var modal = document.getElementById("promoModal");
var span = document.getElementsByClassName("promo-close")[0];

  jQuery(document).ready(function ($) {

   if (sessionStorage.getItem('promomodalWasShown') == null) {
      $('.promomodal').show();
      sessionStorage.setItem('promomodalWasShown', 'true');
   }

    span.onclick = function () {
      jQuery('.promomodal').hide();
    }
    window.onclick = function (event) {
      if (event.target == modal) {
        jQuery('.promomodal').hide();
      }
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM