lowercase
lowercase

Reputation: 1220

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>

Upvotes: 1

Views: 1503

Answers (1)

Vladimir.V.Bvn
Vladimir.V.Bvn

Reputation: 1118

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();
      }
    }
  });

Upvotes: 2

Related Questions