Skip to content

Commit 5f50ff5

Browse files
cookie-II
1 parent 7202949 commit 5f50ff5

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed
Loading
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
7+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8+
<title>cookie-part-II-JS</title>
9+
<link rel="shortcut icon" href="images/js-logo.png" type="image/x-icon">
10+
</head>
11+
12+
<body>
13+
14+
</body>
15+
<h1>Cookie in JS</h1>
16+
<p id="textOne"></p>
17+
<button onclick="checkCookie()">click</button>
18+
<script src="script.js"></script>
19+
20+
</html>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
let textOne = document.getElementById('textOne');
2+
3+
function setCookie(cname, cvalue, exdays) {
4+
const d = new Date();
5+
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
6+
let expires = "expires=" + d.toUTCString();
7+
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
8+
textOne.innerHTML = document.cookie;
9+
}
10+
11+
function getCookie(cname) {
12+
let name = cname + "=";
13+
let decodedCookie = decodeURIComponent(document.cookie);
14+
let ca = decodedCookie.split(';');
15+
for (let i = 0; i < ca.length; i++) {
16+
let c = ca[i];
17+
while (c.charAt(0) == ' ') {
18+
c = c.substring(1);
19+
}
20+
if (c.indexOf(name) == 0) {
21+
return c.substring(name.length, c.length);
22+
}
23+
}
24+
return "";
25+
}
26+
27+
function checkCookie() {
28+
let user = getCookie("username");
29+
if (user != "") {
30+
alert("Welcome again " + user);
31+
} else {
32+
user = prompt("Please enter your name:", "");
33+
if (user != "" && user != null) {
34+
setCookie("username", user, 30);
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)