Alert Box - should hide when only click on (x)

问题: I have simple code for alert box. After only click (x) should hide element. iusse: The problem is that I can click anywhere on the website, then the element automaticall...

问题:

I have simple code for alert box. After only click (x) should hide element.

iusse: The problem is that I can click anywhere on the website, then the element automatically hides. I would like the element to be hidden when only clicking on (x).

document.addEventListener("DOMContentLoaded", function() {
   let dismissed = sessionStorage.getItem("dismissed");
   let alertDiv = document.getElementById("promo");
   let dismissButton = document.getElementById("dismiss");
   if(!dismissed){
     alertDiv.classList.remove("hide");
   }

  addEventListener("click", function(){
    alertDiv.classList.add("hide");
    sessionStorage.setItem("dismissed", true);
  });
});
/* The alert PROMO box */
.promo {
  padding: 10px;
  background-color: #415ca2; /* Blue */
  color: white;
  margin-bottom: 7px;
}
.hide {
display: none;
}

/* 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 */
.closebtnpr:hover {
  color: black;
}
<div class="promo hide" id="promo"> 
  <span class="closebtnpr" id="dismiss">x</span>
  <center>
    <b>U.S. POLO ASSN. DAY!</b><br />
  </center>
</div>

update:

document.addEventListener("DOMContentLoaded", function() {
   let dismissed = sessionStorage.getItem("dismissed");
   let alertDiv = document.getElementById("promo");
   let dismissButton.addEventListener("click", function(){
    alertDiv.classList.add("hide");
    sessionStorage.setItem("dismissed", true);
  });
});

回答1:

let dismissed = sessionStorage.getItem("dismissed");
let dismissButton = document.getElementById("dismiss");
let alertDiv = document.getElementById("promo");

if(!dismissed){
    alertDiv.classList.remove("hide");
}

dismissButton.addEventListener("click", function(){
    alertDiv.classList.add("hide");
    sessionStorage.setItem("dismissed", true);
});

You are storing a session variable, so your box will not show up after the box has been clicked until that session variable is deleted.

  • 发表于 2019-07-05 17:57
  • 阅读 ( 162 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除