Search code examples
cssalertbox

Alert box - How to save close(x) in browser cache


Here I have simple alert box:

/* The alert PROMO box */
.promobox {
  padding: 10px;
  background-color: #415ca2; /* Blue */
  color: white;
  margin-bottom: 7px;
}

/* The close button */
.closebtnpr {
  margin-left: 15px;
  color: white;
  font-weight: bold;
  float: right;
  font-size: 18px;
  line-height: 20px;
  cursor: pointer;
  transition: 0.3s;
}

/* When moving the mouse over the close button */
.closebtn:hover {
  color: black;
}
<div class="promobox">
    <span class="closebtnpr" onclick="this.parentElement.style.display='none';">×</span>
    <center><b>U.S. POLO ASSN. DAY!</b></center>
</div>

When I click on (x) then hide element. But when I refresh page then again is displayed alert box.

How can I remember the choice of closing the alert box until I finish browsing the website?

update2:

sessionStorage.setItem('myCat', 'Tom');

The following example autosaves the contents of a text field, and if the browser is accidentally refreshed, restores the text field content so that no writing is lost.

// Get the text field that we're going to track
let field = document.getElementById("field");

// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
  // Restore the contents of the text field
  field.value = sessionStorage.getItem("autosave");
}

// Listen for changes in the text field
field.addEventListener("change", function() {
  // And save the results into the session storage object
  sessionStorage.setItem("autosave", field.value);
});

Solution

  • You almost got it in your last edit. Use sessionStorage (or localStorage if you want your data to persist). Instead of changing display attribute directly with js use css class, and remove it if user didn't dismiss it before. Use boolean value for sessionStorage variable.

    This code snippet won't work in the sandbox environment

    document.addEventListener("DOMContentLoaded", function() {
       let dismissed = sessionStorage.getItem("dismissed");
       let alertDiv = document.getElementById("alert");
       let dismissButton = document.getElementById("dismiss");
       if(!dismissed){
         alertDiv.classList.remove("hide");
       }
    
    
      addEventListener("click", function(){
        alertDiv.classList.add("hide");
        sessionStorage.setItem("dismissed", true);
      });
    });
    .alert{border: 1px dashed lime; font-size: x-large; display: inline-block}
    .hide{display: none}
    <div class="alert hide" id="alert">
      SOME ANNOYING ALERT HERE!
      <button type="button" id="dismiss">X</button>
    </div>