remembering which webpages have been visited - javascript

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(','))
}

Related

How do I use cookies to create a number that increases on the click of a button and stays the same after multiple website visits (HTML / JS)?

I'm trying to make a basic website that has a text box that will display a counter. The user can click a button to add one to the counter and I'm trying to make it so that the counter can retain its value across multiple distinct visits to the websites. I'm using cookies to solve the retention issue but I'm not sure that's the best solution. As of right now the counter button isn't working at all. I'm very new to HTML and Java. Thank you in advance. Below is my code.
<html>
<head><meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form1" method="post" name="form1">
<p>
<input id="set_Value" name="set_Value" onclick="setValue()" type="button" value="Add 1" />
</p>
<p>
Counter:<label><input id="bbb" name="bbb" type="text" /> </label>
</p>
</form>
<script type="text/javascript">
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 setCookie(cname, value) {
if(document.cookie(cname) == null) {
document.cookie = cname;
}
document.cookie = cname + '=' + value + ';' + ';path=/';
}
function setValue() {
setCookie(Counter, getValue(Counter)+1);
document.getElementById('bbb').value = getValue(Counter);
}
</script>
</body>
</html>

Adjust HTML with javascript

I have a personal time keeper I am putting together for work. We are allotted 50 minutes a week, and I wanted to make a fancy way of keeping track of that time.
I have a method that works:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#example1 {
background-color="#0CD6C7";
}
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').value = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font face="arial">
<input id="time1" value="50:00" size="5"> 50 minutes of personal time per week <br>
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your personal break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1','time2',false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; }
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
Enter in the length of the break in the second input field and that time is subtracted from the total.
To make it look fancier, I want the total time to appear as only text, not as an input field.
This is what I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
I know I need to use innerHTML, but it's just not quite clicking. Any pointers in the right direction would be much appreciated!
Change the below line
var tt1 = document.getElementById(id1).value;
to
var p = document.getElementById(id1);
var tt1 = p.textContent;
This is because, value function is applicable only to input tags. For the other plain text tags like p, headings, etc. textContent should be fetched.
What wrong is since t1 is a p tag, it doesn't have value so tt1.split(':'); will throw an exception. Use innerText instead.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).innerText;
if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0;
if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>

Show div only once per user session? [duplicate]

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>

setting multiple cookies on page load

I am new to programming and I struggle a lot with cookies in JavaScript, so I have used this tutorial here. I used the 'create cookie function' but I am unsure about how to make a function that puts the cookies back into the text boxes on page load. I have looked at W3 Schools and still have no idea. Any ideas?
Here is the create cookie function I used which creates cookies from 'more than one' textbox.
function createCookie(nCookie){
var expDate = new Date();
expDate.setMonth(expDate.getMonth() + 12);
var cookieVal = document.getElementById(nCookie).value;
document.cookie = nCookie + "=" + cookieVal + ";path=/;expires=" +
expDate.toGMTString();}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h2>Working Example</h2>
<form name="myForm" method="get" action="JavaScriptCookies.html" onsubmit="return storeValues(this);">
<fieldset>
<label>Field 1</label><span><input type="text" name="field1" value=""></span>
<label>Field 2</label><span><input type="text" name="field2" value=""></span>
<label>Field 3</label><span><input type="text" name="field3" value=""></span>
<label>Field 4</label><span><input type="text" name="field4" value=""></span>
<span>
<input type="submit" value="Set Cookies">
<input type="button" onclick="showCookies();" value="Retrieve Cookies">
</span>
</fieldset>
</form>
<script type="text/javascript">
function storeValues(form)
{
document.cookie = 'field1=' + form.field1.value;
document.cookie = 'field2=' + form.field2.value;
document.cookie = 'field3=' + form.field3.value;
document.cookie = 'field4=' + form.field4.value;
return true;
}
function showCookies() {
for (var i = 1; i <= 4; i++) {
x = document.getElementsByName("field" + i);
x[0].value = getCookie(x[0].name);
}
return true;
}
function getCookie(cname)
{
var name = cname + "=";
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);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
</script>
</body>
</html>
<script type="text/javascript">
if(field1 = getCookie("field1")) document.myForm.field1.value = field1;
if(field2 = getCookie("field2")) document.myForm.field2.value = field2;
if(field3 = getCookie("field3")) document.myForm.field3.value = field3;
if(field4 = getCookie("field4")) document.myForm.field4.value = field4;
</script>
http://www.w3schools.com/js/js_cookies.asp
BTW if in the EU you need to declare cookie usage

Why does this not work (HTML, CSS and Javascript

I'm having trouble with some code not working, and I'm not sure why. (I am a 1st year Computer Science student as don't know much about this)
<head>
<link rel="stylesheet" type="text/css" href="Task1.css" title="Normal">
<link rel="alternate stylesheet" type="text/css" href="Task1BaW.css" title="Other">
<script type="text/javascript" src="/scripts/styleswitcher.js">
</script>
</head>
<body>
<div id="header"> <!-- header -->
<button onclick="setActiveStyleSheet('Normal')">Change style to default</button>
<button onclick="setActiveStyleSheet('Other')">Change style to Easy view</button>
</div> <!-- end of header-->
Basically I want it to switch to the "Normal" Css when the 1st button is pressed, and switch to the "Other" Css when the 2nd button is pressed.
Thanks.
NB: I've changed the ‘’ to '(thanks for pointing that out, that was a stupid mistake) and not getting any errors that I'm aware of. Still doesn't seem to be working yet. I'm writing this is PSPad, if that helps at all. And trying it in the IE that PSPad opens and Chrome.
Also, changing the CSS should change the background and text size.
styleswitcher.js code:
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}
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 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;
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
If anyone has a simpler way of doing this instead of fixing this, and can explain it to me so I can understand why it works, I'd appreciate it too.
In javascript, you have to use ' or ".
Your quote ‘ and ’ isn't valid.
Since you did that, even StackOverflow's syntax highlighting failed!!
Try using this :
<div id="header"> <!-- header -->
<button onclick="setActiveStyleSheet('Normal')">Change style to default</button>
<button onclick="setActiveStyleSheet('Other')">Change style to Easy view</button>
</div> <!-- end of header-->

Categories

Resources