울러리

토글, 페이지 새로고침 전 상태 유지. (브라우저 쿠키 활용)

· 1년 전 · 503

브라우저 쿠키를 활용해서, 토글등을 페이지 새로 고침후에도 직전 상태를 유지하는 설정입니다.

저는 토글에서만 활용중이고 제 pc에서만 테스트해서, 다른 환경은 어떨지 확신할 수는 없습니다.

모달창, 토글, 스크립트 등에 활용할 수 있지 않을까 싶습니다.

 

 

<? 
// 쿠키 설정 함수   여기에 시간 단위로 입력설정 0.1은 6분 
$kkk[38] = "0.1";
?>

<script> 
        function setCookie(name, value, hours) {
const expires = new Date(Date.now() + <?=$kkk[38];?> * 3600 * 1000).toUTCString();
            document.cookie = `${name}=${value}; expires=${expires}; path=/`;
        }

        // 쿠키 읽기 함수
        function getCookie(name) {
            const cookieArr = document.cookie.split(';');
            for (let i = 0; i < cookieArr.length; i++) {
                const cookiePair = cookieArr[i].trim().split('=');
                if (cookiePair[0] === name) {
                    return cookiePair[1];
                }
            }
            return null;
        }

        // 페이지 로드 시 상태 복원
        window.addEventListener('load', function() {
            const isOpen = getCookie('boardState');
            const detailsElement = document.getElementById('board-details');
            detailsElement.open = (isOpen === 'true');
        });

// 상태 변경 시 쿠키 설정
document.addEventListener('DOMContentLoaded', function() {
    const detailsElement = document.getElementById('board-details');
    detailsElement.addEventListener('toggle', function() {
        setCookie('boardState', this.open, <?=$kkk[38];?>); // PHP에서 설정한 유지 시간 사용
    });
});
    </script>

<details  id="board-details">
 <summary>게시판 목록</summary><!--시간 쿠키설정함-->
내용테스트
</details>

 

|
댓글을 작성하시려면 로그인이 필요합니다. 로그인

개발자팁

개발과 관련된 유용한 정보를 공유하세요. 질문은 QA에서 해주시기 바랍니다.

+
분류 제목 글쓴이 날짜 조회
JavaScript 1년 전 조회 951
PHP 1년 전 조회 1,387
PHP 1년 전 조회 1,613
기타 1년 전 조회 1,478
기타 1년 전 조회 1,322
PHP 1년 전 조회 942
JavaScript 1년 전 조회 631
JavaScript 1년 전 조회 1,134
1년 전 조회 1,382
JavaScript 1년 전 조회 1,347
1년 전 조회 860
1년 전 조회 1,234
1년 전 조회 1,217
1년 전 조회 955
1년 전 조회 504
1년 전 조회 643
1년 전 조회 1,204
1년 전 조회 848
1년 전 조회 744
PHP 1년 전 조회 943
PHP 1년 전 조회 677
OS 1년 전 조회 750
기타 1년 전 조회 543
기타 1년 전 조회 739
기타 1년 전 조회 586
기타 1년 전 조회 465
JavaScript 1년 전 조회 543
PHP 1년 전 조회 598
jQuery 1년 전 조회 669
PHP 1년 전 조회 1,019
🐛 버그신고