Show div only once per user session? [duplicate] - javascript

This question already has answers here:
Show welcome div only once per user / browser session
(3 answers)
Closed 6 years ago.
How would it be done with this? I have jQuery if that would help.
<div id="RLAD-wrapper">
<div id="RLAD">
<p>stuff</p>
</div>
</div>

if(localStorage.getItem("iknowyou")) {
document.body.innerHTML = "You were already here";
} else {
document.body.innerHTML = "Oh. A new guest...";
localStorage.setItem("iknowyou", "true");
}
This utilizes localStorage to store a persistent state across sessions.

You could also do it with cookies:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="mydiv" style="display: none;">
this is a div
</div>
<script
src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="
crossorigin="anonymous"></script>
<script>
$(function() {
// Cookies
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// Validate cookie
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// alert('No cookei');
$('.mydiv').css('display','block');
setCookie("MyCookie", "foo", 7);
}
else {
// alert('yes cookei');
$('.mydiv').css('display','none');
}
});
</script>
</body>
</html>

The code below sets an item in localStorage to Date.now, and checks if it is past 3 days. The setting of the item is in an else statement to prevent the user from getting their time reset every single time they run the website.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Put anything you want here</title>
</head>
<body>
<div id="aDiv">
Div content
</div>
<script>
if(Date.now() - parseInt(localStorage.getItem("pageVisitedTime").getTime(), 10) < 2.592e+8){
document.getElementById("aDiv").style.display = "none";
}
else{
localStorage.setItem("pageVisitedTime", "" + Date.now());
}
</script>
</body>
</html>

Related

Need help sharing a Javascript variable locally between files

I've been developing a speed test typing game for some time now, and I've been stuck on how to take the time you finish from one HTML page (the game itself) to an alternate one (the score page). I've been trying to use import{} export{}, but I'm not 100% sure how they function and so they haven't exactly worked. I'll attach both the game HTML and Javascript code and the score HTML and Javascript code.
<!-- THIS IS THE HTML PAGE FOR THE GAME -->
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Typeboss || Speed Typing Web Game</title>
<link rel="stylesheet" href="../css/gamestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
<script src="../js/gamescript.js" defer></script>
<script src="../../main/js/mainscript.js" type="module" defer></script>
<script src="./scorescript.js" type="module" defer></script>
</head>
<body>
<div id="all">
<div id="stats">
<h1 id="bossHealth" class="stat">BOSS HEALTH:</h1>
<h1 id="time" class="stat"><span id="minutes">0</span>:<span id="seconds">00</span></h1>
</div>
<div id="boss">
<img src="../imgs/boss.png" width="400px" height="400px" id="bossSprite">
</div>
<div id="input">
<h3 id="outcome"></h3>
<center><p id="prompt"></p></center>
<textarea id="userInput" name="TypeBox" rows="4" cols="100" autofocus></textarea>
</div>
</div>
</body>
</html>
// THIS IS THE JAVASCRIPT CODE
let scoreTime;
var seconds = 0;
var minutes = 0;
let score = 0;
const userInput = document.getElementById("userInput");
const promptBox = document.getElementById("prompt");
const outcomeText = document.getElementById("outcome");
const bossHealthtText = document.getElementById("bossHealth");
const timer = document.getElementById("time");
const bossSprite = document.getElementById("bossSprite");
const secondsText = document.getElementById("seconds");
const minutesText = document.getElementById("minutes");
let gameActive = true;
document.addEventListener('keypress', function(event){
if (event.key === 'Enter'){
checkInput();
}
});
let bossHealth = 100;
let multiplier = 10;
let mistakes = 0;
//
const prompts = ["How much wood could a woodchuck chuck if a woodchuck could chuck wood?", "I will not lose another pilot.", "I can't find my keys!", "Live as if you were to die tomorrow.", "Toto, I've got a feeling we're not in Kansas anymore...", "May the force be with you.", "If our lives are already written, it would take a courageous man to change the script.", "An apple a day keeps the doctor away.", "Frankly, my dear, I don't give a damn.", "Hello, world!", "My favorite sport is basketball!", "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", "You only live once, but if you do it right, once is enough.", "I'm the fastest typer in the wild west!", "Frosty the snowman!", "I'm not a big fan of ice cream.", "If birds can fly, then we should too.", "I don't like trucks, they look weird.", "I love typing!", "I'm a rocket man, burning on a fuse out there alone.", "The water was blue and the skies the same, it was summer."];
//GAME INIT
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
function getNewPrompt() {
promptChoice = Math.floor(Math.random() * prompts.length);
let previousPrompt = prompts[promptChoice];
if (previousPrompt === prompts[promptChoice]){
promptChoice = Math.floor(Math.random() * prompts.length);
console.log("COPY OFF");
}
promptBox.innerHTML = prompts[promptChoice];
}
function checkInput(){
if (userInput.value.trim() === promptBox.innerHTML.trim()){
outcome.innerHTML = "Correct";
bossHealth -= 10;
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
let hitSprite = Math.floor(Math.random() *2);
if(hitSprite === 0){
bossSprite.src = "../imgs/bosshit/bosshit1.png";
}
if(hitSprite === 1){
bossSprite.src = "../imgs/bosshit/bosshit2.png";
}
setTimeout(function(){
bossSprite.src = "../imgs/boss.png";
}, 1000);
if (bossHealth <= 0){
console.log("WORKING");
window.location.href = "./score.html";
createScore();
}
getNewPrompt();
userInput.value = null;
}
else{
outcome.innerHTML = "Try again...";
userInput.value = null;
multiplier --;
mistakes ++;
return;
}
}
function gameTimer(){
console.log("working");
setTimeout(function(){
setInterval(function(){
seconds++;
if(seconds === 60){
minutes ++;
seconds = 0;
}
if (seconds < 9){
secondsText.innerHTML = "0" + seconds;
}
if (seconds > 9){
secondsText.innerHTML = seconds;
}
if(minutes < 9){
minutesText.innerHTML = minutes;
}
if(minutes > 9){
minutesText.innerHTML = minutes;
}
if (seconds < 9){
scoreTime = minutes + ":" + "0" + seconds;
}
if (seconds > 9){
scoreTime = minutes + ":" + seconds;
}
timePoints = minutes + seconds * 2;
return scoreTime;
return timePoints;
}, 1000)
}, 1000);
}
function game(){
gameTimer();
getNewPrompt();
createHeart();
}
function createScore(){
let bonus = Math.floor(Math.random() * 500);
score = timePoints * multiplier + bonus;
export { score };
}
game();
<!-- THIS IS THE SCORE HTML PAGE -->
<!DOCTYPE html>
<!DOCTYPE html>
<html onclick="celebrate()">
<head>
<meta charset="utf-8">
<title>Typeboss || Your Score!</title>
<link rel="stylesheet" href="../css/scorestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
</head>
<body>
<center><h1 style="color: whitesmoke;" id="header">YOU BEAT THE BOSS!</h1></center>
<center><p>(CLICK FOR VICTORY MUSIC)</p></center>
<h3 id="time">TIME:</h3>
<p id="playertime"></p>
<h3 id="score">SCORE:</h3>
<p id="playertime"></p>
<h3 id="mistakes">MISTAKES:</h3>
<p id="playertime"></p>
<h2 id="highscore"></h2>
<button id="redirect">BACK TO HOME</button>
</body>
<script type="module" src="../js/gamescript.js" defer></script>
</html>
// AND HERE IS THE SCORE'S CODE
winMusic = new Audio();
winMusic.src = "./winmusic.mp3";
function celebrate(){
winMusic.play();
winMusic.loop = tru
}
import { score } from "./gamescript.js";
const scoreText = document.getElementById("score");
scoreText.innerHTML = score + " points!"
I hope I can get this issue resolved, and I hope this post was clear enough to understand. This is my first post on stack so please do let me know if I formatted it wrong, and any feedback that could make it easier to understand in the future. Thank you in advance and have a good day.
use cookie for saving variables!
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
You can use Session Storage or for this.

get value for a cookie from a bootrap modal with js

I'm trying to create a modal that has 2 options: yes or no. When a user selects no I will create a condition if value=no then do not display modal.
The issue is that I cannot accomplish it. If is answer is yes I can manipulate the info, I need to display a modal asking a question, get the users answer and based on this and do something every 15 days.
my code is currently not working properly
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
$('#hewant').on('click', function() {
var valyes = $(this).text();
console.log(valyes);
});
$('#hedont').on('click', function() {
var valno = $(this).text();
console.log(valno);
});
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
$("#myModalcashout").modal();
user = "testing me";
if (user != "" && user != null) {
setCookie("username", user, 15);
}
}
}
</script>
<body onload="checkCookie()">
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<div id="hewant" value="yes"> yes i am </div>
<div id="hedont" value="no"> no i dont</div>
</div>
</div>
</div>
</div>
</body>
I restructured your code for you. For starters you only need 1 listener for both buttons, which can be assigned using class on the buttons in the modal (which I changed from div to button tags.
Note: "Run this code snippet" will not work in this sand boxed environment in regards to cookie manipulation so you will have to test this yourself.
There is now a showModal() function that you will call on load that is responsible for showing your modal and attaching a click listener to both buttons on the modal.
When the user clicks yes or no on the modal we get their answer and pass it to checkCookie() function which does as you ask.
I replaced your create and set cookie functions with ones that are tested and work (also added eraseCookie()) there is a great explanation about all 3 functions Here
showModal();
function showModal() {
// only show modal if cookie for the user is null
var user = readCookie("username");
if (user != null) {
alert("Welcome again " + user);
}
else {
user = "testing me";
$("#myModalcashout").modal();
// add listener on buttons
$('.modalButton').on('click', function() {
$('#myModalcashout').modal().hide();
var answer = $(this).val();
console.log(answer);
// create a cookie with the users answer to the modal
createCookie("username", answer, 15);
});
}
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<button class="modalButton" value="yes"> yes i am </button>
<button class="modalButton" value="no"> no i dont</button>
</div>
</div>
</div>
</div>

Suggestions with JavaScript Cookies

I am trying to learn cookies in JavaScript. I have already made it possible to save a text as a cookie and view the what is inside the cookie on another page.
What I would like to do now is to make another box like the one I have before but in this box I want to enter rgb color code which will give the cookie page 2 the color which has been saved in the cookie by the user. Hope you understood my question and can help me as much as possible.
Here is my code:
Cookie Page 1:
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Cookies side 1</title>
</head>
<body>
<nav>
<ul>
<li>Cookies 1</li>
<li>Cookies 2</li>
</ul>
</nav>
<section id="cookieadmin">
<h3>Save/Delete a cookie</h3>
<label>Write a text
<input id="textTxt" type="text" placeholder="...write here">
</label>
<input id="saveCookieBtn" type="button" value="Save cookie">
<input id="deleteCookieBtn" type="button" value="Delete cookie">
<p id="cookiestatus"></p>
</section>
<script>
(function(){
var textTxt;
var saveCookieBtn, deleteCookieBtn;
var cookiestatus;
function init(){
setHTMLObjects();
setEvents();
checkIfCookieExists();
}
function setEvents(){
saveCookieBtn.addEventListener("click", saveCookie);
deleteCookieBtn.addEventListener("click", deleteCookie);
}
function deleteCookie(){
var dateObject = new Date();
dateObject.setDate(dateObject.getDate() - 1);
document.cookie = "text=;expires=" + dateObject.toUTCString();
checkIfCookieExits();
}
function saveCookie(){
var dateObject = new Date();
dateObject.setDate(dateObject.getDate() + 7);
document.cookie = "text=" + textTxt.value + ";expires=" + dateObject.toUTCString();
checkIfCookieExists();
}
function setHTMLObjects(){
textTxt = document.getElementById("textTxt");
saveCookieBtn = document.getElementById("saveCookieBtn");
deleteCookieBtn = document.getElementById("deleteCookieBtn");
cookiestatus = document.getElementById("cookiestatus");
}
function checkIfCookieExists(){
var message;
if(document.cookie){
message = "Cookie exists";
}else
{
message = "Cookie does not exist";
}
cookiestatus.innerHTML = message;
}
window.onload = init;
}())
</script>
</body>
</html>
Cookie Page 2:
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Cookie 2s</title>
</head>
<body>
<nav>
<ul>
<li>Cookies 1</li>
<li>Cookies 2</li>
</ul>
</nav>
<p id="cookiestatus"></p>
<script>
(function(){
var cookiestatus;
function init(){
setHTMLObjects();
checkIfCookieExists();
}
function setHTMLObjects(){
cookiestatus = document.getElementById("cookiestatus");
}
function checkIfCookieExists(){
var message;
if(document.cookie){
var cookielist = document.cookie.split("=");
var value = cookielist[1];
message = "Cookie exists: " + value;
}else
{
message = "Cookie does not exist";
}
cookiestatus.innerHTML = message;
}
window.onload = init;
}())
</script>
</body>
</html>
You can create an textbox input element where the user can enter the hexadecimal color value they desire for that page, and store its value as the cookie. Since you already have the functions that handle cookie setting and getting, here's a sample of how you could retrieve the color value.
var input = document.getElementById("colorInput");
input.addEventListener("keydown", function() {
setTimeout(function() {
document.getElementById("value").innerHTML = input.value;
}, 500);
});
<input id="colorInput" type="text" />
<p>Input value: <span id="value"></span></p>
You would also have to add some kind of validation check on input value to make sure it's a proper hex value.
As for the cookie itself, you could store all colors for different pages as a stringified JSON object at the root level, or set different cookies at each page level, in which case mind the names you use for each one of them.
Edit:
I made a demo of how your code could work. Here's the code for each page.
Page 1:
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Cookies side 1</title>
</head>
<body>
<nav>
<ul>
<li>Cookies 1</li>
<li>Cookies 2</li>
</ul>
</nav>
<section id="cookieadmin">
<h3>Save/Delete a cookie</h3>
<label>Write a text
<input id="textTxt" type="text" placeholder="...write here">
</label>
<input id="saveCookieBtn" type="button" value="Save cookie">
<input id="deleteCookieBtn" type="button" value="Delete cookie">
<input id="colorInput" type="text" />
<input id="saveColorBtn" type="button" value="Save color" /><span id="valMsg"></span>
<p>Input color: <span id="colorValue"> </span></p>
<p id="cookiestatus"></p>
</section>
<script>
function init() {
setHTMLObjects();
setEvents();
checkIfCookieExists();
}
function setEvents() {
saveCookieBtn.addEventListener("click", saveCookie);
deleteCookieBtn.addEventListener("click", deleteCookie);
saveColorBtn.addEventListener("click", saveColor);
}
function deleteCookie() {
var dateObject = new Date();
dateObject.setDate(dateObject.getDate() - 1);
document.cookie = "text=;expires=" + dateObject.toUTCString();
checkIfCookieExits();
}
function saveCookie() {
var dateObject = new Date();
dateObject.setDate(dateObject.getDate() + 7);
document.cookie = "text=" + colorInput.value + ";expires=" + dateObject.toUTCString();
checkIfCookieExists();
}
function setHTMLObjects(){
textTxt = document.getElementById("textTxt");
saveCookieBtn = document.getElementById("saveCookieBtn");
deleteCookieBtn = document.getElementById("deleteCookieBtn");
cookieStatus = document.getElementById("cookiestatus");
colorInput = document.getElementById("colorInput");
colorValue = document.getElementById("colorValue");
saveColorBtn = document.getElementById("saveColorBtn");
valMsg = document.getElementById("valMsg");
}
function checkIfCookieExists() {
var message;
if (document.cookie) {
message = "Cookie exists";
} else {
message = "Cookie does not exist";
}
cookiestatus.innerHTML = message;
}
function saveColor() {
var color = colorInput.value,
msg;
if( isHex(color) ) {
color = '#'+color;
msg = '<em style="color:green;">Valid hex value!</em>';
colorValue.innerHTML = color;
document.body.style.background = color;
saveCookie();
} else {
colorInput.value = '';
msg = '<em style="color:red;">Invalid hex value!</em>';
}
valMsg.innerHTML = msg;
setTimeout(function() {
valMsg.innerHTML = "";
}, 5000);
}
function isHex(str) {
/* Author: Royi Namir
* Ref: http://stackoverflow.com/questions/8027423/how-to-check-if-a-string-is-a-valid-hex-color-representation#answer-8027444
*/
var isHex = /(^[0-9A-F]{6}$)|(^[0-9A-F]{3}$)/i.test(str);
return isHex;
}
var saveCookieBtn, deleteCookieBtn, saveColorBtn, cookiestatus, colorInput;
window.addEventListener("load", init, false);
Page 2:
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Cookie 2s</title>
</head>
<body>
<nav>
<ul>
<li>Cookies 1</li>
<li>Cookies 2</li>
</ul>
</nav>
<p id="cookiestatus"></p>
<script>
(function(){
var cookiestatus;
function applyCookieColor() {
var color = getCookie();
// Change text color of element
elemColor.style.color = color;
// OR change background color of element
elemColor.style.backgroundColor = color;
}
function init(){
setHTMLObjects();
checkIfCookieExists();
applyCookieColor();
}
function setHTMLObjects(){
cookiestatus = document.getElementById("cookiestatus");
elemColor = document.getElementById("elemColor");
}
function checkIfCookieExists(){
var message;
if(document.cookie){
var cookielist = document.cookie.split("=");
var value = cookielist[1];
message = "Cookie exists: " + value;
}else
{
message = "Cookie does not exist";
}
cookiestatus.innerHTML = message;
}
function getCookie() {
/* code to get the cookie */
}
window.onload = init;
}());
</script>
</body>
</html>
Note:
For the JS code in Page 2 to work properly, you need to complete the getCookie() function, which I left blank since I assume you already got it.
Edit 2:
I found a really complete cookie handling script in the https://developer.mozilla.org site. You should use it for cookie handling.
JS:
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
All modern browsers support LocalStorage, use it instead.
To save data use
var myVar = localStorage.setItem('myVar', 'myValue');
To get data:
var myVar = localstorage.getItem('myVar'); // will get 'myValue'
To check compatibility for old versions use:
if(typeof(Storage)!=='undefined') {
// you code here
} else {
// Oops, no Local Storage
}
Have fun!

remembering which webpages have been visited

I am trying to make a website where it picks a random webpage ( i have 35) when you press on a button. However I want it to only go to each site once. I am thinking that a cookie could do the job but I am unsure how to do it.
So I am trying to have cookies remember which pages have been visited and which have not.
I am quite new to JavaScript so please be nice.
My JavaScript:
function myFunction() {
var tal=Math.floor((Math.random() * 35) + 1)
window.location.href = "Sang"+tal+".html";
}
One of my webpages:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Gæt en sang</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="Test.js"></script>
</head>
<body>
<audio class="hidden" controls autoplay>
<source src="horse.ogg" type="audio/ogg">
<source src="pokemon.mp3" type="audio/mpeg">
</audio>
<div id="header">
<h2> Gæt sangen og hejs flagstangen!</h2>
</div>
<div id="left">
<ul> Hvilken sang er dette?
</br>
<button type="button" onclick="myFunction()">
<li> World we must defend </li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Pokemon theme</li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Gotta Catch 'em All<li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> You teach me i teach you <li>
</button>
</ul>
</div>
</div>
<p id="Test"></p>
</body>
</html>
Taken from https://stackoverflow.com/a/24103596/1029988
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
you can use these two to set and read an array of pages visited:
function myFunction() {
var cookie = readCookie('pages') || '';
var pages = cookie.split(',');
var tal=Math.floor((Math.random() * 35) + 1);
while (pages.indexOf(tal) > -1) { // randomize until you reach a number not stored in the cookie
tal=Math.floor((Math.random() * 35) + 1);
}
window.location.href = "Sang"+tal+".html";
pages.push(tal);
createCookie('pages', pages.join(','))
}
the while loop could take some time to execute, though, especially towards the end of the 35 possible pages (i.e. when only 5 number are left). You can make the code more efficient by removing the stored numbers from the list of choices:
function myFunction() {
var cookie = readCookie('pages') || '';
var pages = cookie.split(',');
var available_choices = [];
for (var i = 1; i < 36; i++) {
if (pages.indexOf('' + i) == -1) {
available_choices.push(i);
}
}
var tal=available_choices[Math.floor(Math.random() * available_choices.length - 1)];
window.location.href = "Sang"+tal+".html";
pages.push(tal);
createCookie('pages', pages.join(','))
}

Reading & using cookie values with javascript

Just off the get go I am incredibly new to javascript, apologies for any silly comments or obvious mistakes in advance.
This is what I'm currently working with:
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" name="ER_ID">
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
document.forms['CurrencyChoice'].elements['ER_ID'].value = '';
</script>
</form>
</div>
I want the value from the following cookie "ER%5fID" to be read and then inserted in the value=''field above.
To be completely honest I'm at abit of a loss as I'm not sure what the best way is to read the cookie's value and then have its value inserted where I want.
Once again apologies for any newbie mistakes. I'm having to learn javascript on the fly and I had to start a few days ago.
So I have spent a fair amount of time today trying to figure out what I need which I think is this:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
However I'm still unsure as to how to have the appropriate result return within the value field?
Thanks in advance for any assistance.
I am sorry I just do not care to rewrite this, the W3Scools tutorial on cookies is quite comprihensive and even gives you fully completed functions for reading and writing cookies.
It's also a good resource for general JS learning so you should definitely check it out.
The code there is as follows:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
And usage is:
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
But you can read more in W3Scools own website.
EDIT : So here is the promised fully functional sample in your specific case:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Cookie Example</title>
<script type="text/javascript">
//adds the [String].trim() method to the [String] object if missing
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var cookieName = "ER_ID";
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function setOptionFromCookie() {
var select = document.getElementById('ER_ID'), index, value = getCookie(cookieName);
index = select.options.length;
while(index--) {
if(select.options[index].value == value) {
break;
}
}
if(index > -1) {
select.selectedIndex = index;
} else {
alert('no such value in selection');
}
}
function setValue() {
var value = document.getElementById('value').value;
setCookie(cookieName, value, 365);
}
</script>
</head>
<body>
The value that will go into the cookie "ER_ID": <input id="value" value="2" />
<br/>
<button onclick="setValue()">Set Cookie</button>
<button onclick="setOptionFromCookie()">Set Option from cookie</button>
<hr />
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" id="ER_ID" name="ER_ID">
<option value="1" selected="selected">Select Currency</option>
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
</script>
</form>
</div>
</body>
</html>
Because I do not have such a cookie in my browser I also made a possibility for you to set the cookie. But it should be fairly easy to understand. Simply set the cookie first and then press "Set Option from cookie" to read the cookie and set the option based on the value.

Categories

Resources