울러리

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

· 1년 전 · 412

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

저는 토글에서만 활용중이고 제 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년 전 조회 896
PHP 1년 전 조회 1,344
PHP 1년 전 조회 1,517
기타 1년 전 조회 1,411
기타 1년 전 조회 1,207
PHP 1년 전 조회 829
JavaScript 1년 전 조회 582
JavaScript 1년 전 조회 1,065
1년 전 조회 1,299
JavaScript 1년 전 조회 1,297
1년 전 조회 814
1년 전 조회 1,162
1년 전 조회 1,159
1년 전 조회 859
1년 전 조회 413
1년 전 조회 605
1년 전 조회 1,158
1년 전 조회 737
1년 전 조회 691
PHP 1년 전 조회 906
PHP 1년 전 조회 626
OS 1년 전 조회 706
기타 1년 전 조회 499
기타 1년 전 조회 690
기타 1년 전 조회 551
기타 1년 전 조회 439
JavaScript 1년 전 조회 489
PHP 1년 전 조회 552
jQuery 1년 전 조회 631
PHP 1년 전 조회 985
🐛 버그신고