울러리

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

· 1년 전 · 683

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

저는 토글에서만 활용중이고 제 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년 전 조회 1,138
PHP 1년 전 조회 1,569
PHP 1년 전 조회 1,789
기타 1년 전 조회 1,681
기타 1년 전 조회 1,511
PHP 1년 전 조회 1,120
JavaScript 1년 전 조회 807
JavaScript 1년 전 조회 1,326
1년 전 조회 1,720
JavaScript 1년 전 조회 1,558
1년 전 조회 1,056
1년 전 조회 1,430
1년 전 조회 1,426
1년 전 조회 1,145
1년 전 조회 684
1년 전 조회 808
1년 전 조회 1,426
1년 전 조회 1,058
1년 전 조회 944
PHP 1년 전 조회 1,123
PHP 1년 전 조회 906
OS 1년 전 조회 953
기타 1년 전 조회 753
기타 1년 전 조회 957
기타 1년 전 조회 753
기타 1년 전 조회 623
JavaScript 1년 전 조회 766
PHP 1년 전 조회 833
jQuery 1년 전 조회 866
PHP 1년 전 조회 1,226