자바스크립트 팝업 만들기 (feat. ChatGPT)

워드프레스에는 다양한 팝업 플러그인이 있기 때문에 팝업 플러그인을 사용하여 쉽게 팝업을 표시할 수 있습니다. 플러그인에서 제공하는 기능을 사용하여 팝업을 표시할 페이지, 빈도 등을 설정하는 것도 가능합니다. 심플한 이미지 팝업부터 드래그 앤 드롭 방식으로 쉽게 팝업을 만들 수 있는 플러그인("사용이 쉬운 워드프레스 팝업 플러그인 Brave Popup Builder" 참고)까지 다양한 플러그인이 있습니다.

티스토리 블로그에 쿠팡 배너를 테스트로 팝업으로 표시하도록 설정해보았습니다. 티스토리의 경우 자바스크립트를 사용하여 팝업을 만들 수 있습니다. 다만, 표시할 페이지 등은 자세하게 세팅하는 데에는 제약이 있습니다.

자바스크립트 팝업 만들기 (feat. ChatGPT)

자바스크립트 팝업 만들기 (feat. ChatGPT)

프로그래밍 언어에 익숙하지 않은 경우 구글링하여, 많은 검색 결과 중에서 상황에 맞는 것을 선별하여 테스트하는 작업을 거쳐야 합니다.

요즘 ChatGPT가 핫한데요. 챗GPT를 활용하면 많은 검색 결과 중에서 상황에 적당한 것을 선별하여 직접 코드를 만들어줍니다. 코드를 확인하여 약간 수정하여 활용할 수 있을 정도로 꽤 괜찮은 결과를 제시하는 것 같습니다.

※ 삽입한 영상이 비공개 또는 삭제되어 다른 영상으로 교체했습니다. 이 글을 작성 후에 유료 버전인 ChatGPT Plus가 출시되었습니다. 저는 챗GPT 유료 요금제에 가입하였습니다😄😄 부정확한 답변도 많지만 잘 활용하면 다양하게 이용할 수 있으리라 생각됩니다.

참고로 OpenAI의 ChatGPT를 사용하여 자동으로 포스팅하는 것도 가능합니다.

질문을 영어로 하되, 짧은 문장으로 명확하게 원하는 내용을 제시하면 ChatGPT가 알아서 이해하여 적당한 코드를 제시해 주는 것 같습니다.

다음은 ChatGPT가 제시하는 자바스크립트 팝업 코드입니다. 페이지가 로드되면 5초 후에 팝업이 표시되고 쿠키 시간을 지정하여 반복적으로 표시하지 않도록 요청해보았습니다.

자바스크립트 코드:

<script>
  function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  function showPopup() {
    var popup = document.getElementById("popup");
    popup.style.display = "block";
    setCookie("popupDisplayed", Date.now(), 3);
  }

  function checkPopupDisplay() {
    var lastDisplayed = getCookie("popupDisplayed");
    if (lastDisplayed) {
      var threeHours = 3 * 60 * 60 * 1000;
      if (Date.now() - lastDisplayed > threeHours) {
        setTimeout(showPopup, 5000);
      }
    } else {
      setTimeout(showPopup, 5000);
    }
  }
  checkPopupDisplay();
</script>

CSS 코드:

#popup {
    position: fixed;
    bottom: 0;
    right: 0;
}

HTML 코드는 제시되지 않아서 HTML 코드도 부탁하니 간단한 샘플을 알려주네요.

<div id="popup" style="display: none;">
  <div class="popup-content">
    <div class="popup-header">
      <span class="close" onclick="document.getElementById('popup').style.display='none'">&times;</span>
      <h2>Popup Title</h2>
    </div>
    <div class="popup-body">
      <p>Popup content goes here.</p>
    </div>
  </div>
</div>

코드 중에서 궁금한 점이 있으면 질문하면 친절하게 설명해 주네요. 코드에 주석을 원하는 경우 주석을 요청할 수 있습니다.

<script>
  // Function to set a cookie with a specified name, value and expiry date
  function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    // Set the expiration time in milliseconds (number of days * 24 hours/day * 60 minutes/hour * 60 seconds/minute * 1000 milliseconds/second)
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  // Function to get the value of a cookie with a specified name
  function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  // Function to show the popup
  function showPopup() {
    var popup = document.getElementById("popup");
    popup.style.display = "block";
    // Set a cookie to track when the popup was last displayed
    setCookie("popupDisplayed", Date.now(), 3);
  }

  // Function to check if the popup should be displayed
  function checkPopupDisplay() {
    var lastDisplayed = getCookie("popupDisplayed");
    if (lastDisplayed) {
      // Get the time in milliseconds for 3 hours
      var threeHours = 3 * 60 * 60 * 1000;
      if (Date.now() - lastDisplayed > threeHours) {
        // If it has been more than 3 hours since the last display, show the popup after 5 seconds
        setTimeout(showPopup, 5000);
      }
    } else {
      // If the "popupDisplayed" cookie does not exist, show the popup after 5 seconds
      setTimeout(showPopup, 5000);
    }
  }
  // Call the checkPopupDisplay function when the page loads
  checkPopupDisplay();
</script>

위의 코드에 오류가 있을 수 있으므로 검토하여 적절히 수정한 후에 활용할 수 있습니다. 상기 코드에서 쿠키 시간 부분을 체크하여 적절히 수정하시기 바랍니다. 의심스러운 부분은 다시 질문을 하면 수정된 코드를 제시합니다.

ChatGPT는 현재 무료로 이용이 가능합니다. 프로그래밍 언어를 배울 때에도 도움이 될 것 같습니다.

참고

일부 글에 제휴 링크가 포함될 수 있으며 파트너스 활동으로 일정액의 수수료를 받을 수 있습니다.

댓글 남기기

* 이메일 정보는 공개되지 않습니다.