반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

ZeroToHunnit Coding

[Javascript] 로컬스토리지로 하루 동안 안보이게 하는 팝업 만들기 본문

JAVASCRIPT

[Javascript] 로컬스토리지로 하루 동안 안보이게 하는 팝업 만들기

0에서100 2024. 1. 17. 12:14
728x90
반응형

위와 같이 그냥 닫기를 누르면 새로고침해도 다시 뜨고, 오늘 하루 보지 않기를 누르면 새로고침해도 뜨지 않다가 하루 뒤에 열리는 팝업을 만들어보았다.

 

보통 쿠키로 많이 만드는데 현재 시간만 저장하면 되는데 서버와 통신해야하나 싶어서 로컬스토리지가 더 효율적일거같아 로컬스토리지에 저장하는 방식으로 만들었다.

 

HTML

  <div class="main-popup">
    <div class="wrapper">
      <div class="content-box">
        <p>contents</p>
      </div>
      <div class="btn-wrap">
        <button class="btn-close"><span>닫기</span></button>
        <button class="btn-oneday-close"><span>오늘 하루 보지 않기</span></button>
      </div>
    </div>
  </div>

 

CSS

button {
  border: 0;
  background: none;
  cursor: pointer;
}

.main-popup {
  position: fixed;
  z-index: 999;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: block;
  background-color: #fff;
  border: 4px solid black;
}

.off {
  display: none;
}

.content-box {
  width: 400px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40px;
}

.btn-close {
  position: absolute;
  top: 17px;
  right: 17px;
  font-size: 30px;
  color: #444;
}

.btn-oneday-close {
  width: 100%;
  height: 60px;
  background-color: #e5e5e5;
  text-align: center;
  color: black;
  font-size: 30px;
}

off 클래스를 떼었다 붙였다 하는 방식으로 했다. off를 붙이면 화면에 팝업이 뜨지 않는다.

 

JAVASCRIPT

const toggleMainPopup = function() {
 
  const handleStorage = {
    setStorage: function (name, exp) {
      let currentDate = new Date();
      currentDate = currentDate.setTime(currentDate.getTime() + exp * 24 * 60 * 60 * 1000);
      localStorage.setItem(name, currentDate);
    },
    getStorage: function (name) {
      let currentTime = new Date().getTime()
      let storedTime = parseInt(localStorage.getItem(name));

      if (!storedTime || storedTime <= currentTime) {
        return null;
      }

      return true;
    }
  };

    const mainPopup = document.querySelector(".main-popup");
    const btnOnedayClose = mainPopup.querySelector(".btn-oneday-close");
    const btnClose = mainPopup.querySelector(".btn-close");

    if (handleStorage.getStorage("today")) {
        mainPopup.classList.add("off");
    } else {
        mainPopup.classList.remove("off");
    }

    btnOnedayClose.addEventListener("click", function() {
        handleStorage.setStorage("today", 1);
        mainPopup.classList.add("off");
    });

    btnClose.addEventListener("click", function() {
        mainPopup.classList.add("off");
    });
};

toggleMainPopup();

우선 함수를 변수에 담아서 마지막에 함수를 실행시켜주었다.

 

handleStorage라는 object자료를 만들었다. 

setStorage에는 현재 시간을 받아 현재시간 + 만료시간을 로컬스토리지에 저장하는 코드를 짰다. exp에 곱해진 수들은 타임의 단위가 ms이기 때문에 24시간 60분 60초 1000밀리세컨즈를 곱해준 것이다.

getStorage에는 현재 시간을 ms단위로 받아와 저장된 시간을 가져와서 조건문으로 저장된 시간이 없거나 현재 시간이 저장된 시간을 초과하면 팝업이 보이게, 반대 상황이면 안보이게 짜놓는다.

그리고 조건문으로 스토리지에 today라는 값이 있는지 없는지에 따라 팝업이 보일지 안보일지 판단을 먼저 해주고 어떤 닫기 버튼을 눌렀느냐에 따라 다르게 코드를 짰다.

 

아직 로컬스토리지 다루는 법에 대해 미숙하지만 논리적으로 생각해보고 하나하나 따져가면서 차근차근 하다보니 오류 없이 완성하게 되었다. 

728x90
반응형