코밍이의 하루

[JQuery] JQuery-cookie 플러그인 활용하기 본문

웹언어 공부/JQuery

[JQuery] JQuery-cookie 플러그인 활용하기

코밍이 2021. 8. 24. 11:39

1. 개발 환경

구분 내용
사용 언어 HTML5, CSS3, JS, jQuery 
개발환경 Visual Studio Code
참고 도서 [Do it] 자바스크립트 + 제이쿼리 입문
웹브라우저 Chrome

2. 주요 문법

1) jquery-cookie 플러그인

- 쿠키를 생성하고 쿠키 만료일을 설정할 수 있음

- 쿠키 : 사이트를 방문한 사용자의 소량의 브라우저 정보를 저장할 수 있는 공간

- 하나의 도메인 당 최대 20개를 생성할 수 있고 최대 4KB까지 저장할 수 있음.

- 쿠키를 사용하여 '오늘 하루 동안 이 창 열지 않기'나 '최근에 본 상품' 기능 구현 가능

- jquery-cookie 플러그인 설치 : http://cdnjs.com - jquery-cookie 검색

 

cdnjs - The #1 free and open source CDN built to make life easier for developers

Simple. Fast. Reliable. Content delivery at its finest. cdnjs is a free and open-source CDN service trusted by over 12.5% of all websites, serving over 200 billion requests each month, powered by Cloudflare. We make it faster and easier to load library fil

cdnjs.com

 

2) jquery-cookie 메소드 사용법

종류 예시 설명
$.cookie("쿠키 이름","쿠키 값", {expires:만료일, path:"저장 경로"}); $.cookie("myName", "hello", {expire:3,path:"/"}); 쿠키 이름: "myName"
쿠키 값: "hello"
expires 값: 3(3일 후 자동 소멸)
path 값: "/"(최상위 폴더에 저장)
$.cookie("쿠키 이름"); $.cookie("myName") "myName"이라는 이름으로 저장된 쿠키의 값 반환
$.removeCookie("쿠키 이름"); $.removeCookie("myName") "myName"이라는 이름으로 저장된 쿠키를 제거

 

3. 소스 코드 및 실행 결과

1) jquery_plugin_4_test.html

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title> Plugin </title>
		<style>
			*{margin: 0;padding: 0;}
			body{font-size: 12px;}
			input{vertical-align: middle;}
			#notice_wrap{
				width: 300px;
				position: absolute;
				left: 30px;
				top: 30px;
				box-shadow:0 0 8px #000;
			}
			.closeWrap{
				background-color: #000;
				color:#fff;
				text-align: right;
				padding:5px 10px;
			}
			.closeWrap button{
				margin-left: 20px;
				cursor:pointer;
			}
		</style>
		<script src="js/jquery.js"></script>
		<script src="js/jquery.cookie.js"></script>
		<script>
			$(function() {
				if($.cookie("popup") == "none"){
					$("#notice_wrap").hide();
				}

				var $expChk = $("#expiresChk");
				$(".closeBtn").on("click", closePop);

				function closePop(){
					if($expChk.is(":checked")) {
						$.cookie("popup","none", {expire:3, path:"/"});
					}
					$("#notice_wrap").fadeOut("fast");
				}
			});
		</script>
	</head>
	<body>
		<div id="notice_wrap">
			<img src="images/pic_t1.jpg" alt="공지사항">
			<p class="closeWrap">
				<input type="checkbox" name="expiresChk" id="expiresChk">
				<label for="expiresChk">3일 동안 이 창 열지않기</label>
				<button class="closeBtn">닫기</button>
		</p>
		</div>  
	</body>
</html>

 

jquery_plugin_4_test.html