본문 바로가기

DEVELOP

[Javascript] 오늘 하루 팝업 닫기

728x90

오늘 하루 팝업 창 닫기

쿠키를 구워서 오늘 하루 팝업 창을 닫을 수 있다.

setCookie 와 getCookie 함수를 사용하여 오늘하루닫기 클릭시 하루동안 창이 안열리게 할 것 이다.

 

먼저 팝업 창 HTML 마크업 작업을 한다.

<div class="home-popup">
  <div id="agreePopup" class="agree-popup-frame">
    <div class="agree-popup-inner">
      <a href="javascript:todayClose('agreePopup', 1);" class="today-x-btn">오늘하루닫기</a>
      <a href="javascript:fadeOutPop('#agreePopup');" class="x-btn">닫기</a>
      <a href="javascript:;" class="use-btn" target="_blank">동의하고 신규 서비스 사용하기</a>
    </div>
  </div>
</div>

우린 a태그의 오늘하루닫기를 클릭 시, 클릭 한 기준으로 부터 24시간 동안 해당 팝업 창을 보이지 않게 할 것이다.

 

<script>
 // * today popup close
  todayOpen('agreePopup');
  // 창열기  
  function todayOpen(winName) {
    var blnCookie = getCookie(winName);
    var obj = eval("window." + winName);
    console.log(blnCookie);
    if (!blnCookie) {
      obj.style.display = "block";
    } else {
      obj.style.display = "none";
    }
  }
  // 창닫기  
  function todayClose(winName, expiredays) {
    setCookie(winName, "expire", expiredays);
    var obj = eval("window." + winName);
    obj.style.display = "none";
  }
  // 쿠키 가져오기  
  function getCookie(name) {
    var nameOfCookie = name + "=";
    var x = 0;
    while (x <= document.cookie.length) {
      var y = (x + nameOfCookie.length);
      if (document.cookie.substring(x, y) == nameOfCookie) {
        if ((endOfCookie = document.cookie.indexOf(";", y)) == -1)
          endOfCookie = document.cookie.length;
        return unescape(document.cookie.substring(y, endOfCookie));
      }
      x = document.cookie.indexOf(" ", x) + 1;
      if (x == 0)
        break;
    }
    return "";
  }

  // 24시간 기준 쿠키 설정하기  
  // 만료 후 클릭한 시간까지 쿠키 설정  
  function setCookie(name, value, expiredays) {
    var todayDate = new Date();
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";"
  }
</script>