Suggestions with JavaScript Cookies - javascript

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!

Related

Unable to call JavaScript method based on button element "id"

I am following a tutorial from Head First Javascript. In the tutorial, the showBlogs() method is called via the following html code
HTML button
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
function showBlogs(numberOfEntries){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
However, when I create another button and access it via javascript and call the same method with the event handler - nothing happens.
Button
<button type="button" id="showAllBlogs">Show All Posts</button>
Access Button within Javascript
const showBlogsButton = document.getElementById('showAllBlogs');
Call the showBlogs method
showBlogsButton.addEventListener('click', showBlogs);
I did try creating another function say 'foo()' and I called foo() with the new button and I was able to invoke the method. But when I call the showBlogs() method, nothing happens.
JAVASCRIPT CODE
`
//dom elements
const blogsDOM = document.getElementById('blog');
const query = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const showBlogsButton = document.getElementById('showAllBlogs');
// Constructor
function Blog(body, dateString){
this.body = body;
this.date = new Date(dateString);
this.toString = function(){
return this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body;
};
this.toHTML = function(highlight){
var htmlPost = "";
//determine to highlight post
htmlPost += highlight ? "<p style='background-color: #EEEEEE'>" : "<p>";
//generate formatted html
htmlPost += this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body + "</p>";
//return html
return htmlPost;
};
this.containsText = function(text){
return this.body.toLowerCase().indexOf(text.toLowerCase()) > -1;
};
}
//Array of blogs
var blogs = [
new Blog("Got the new cube I ordered", "01/25/1986"),
new Blog("This new cube works just fine", "02/22/2000"),
new Blog("This is going to be the third one", "03/23/2005"),
new Blog("This is the final one", "03/21/2020")
]
blogs.sort(function(blog1, blog2){ return blog2.date - blog1.date; })
function getDaysBetweenDates(date1, date2){
var daysBetween = (date2 - date1) / (1000 * 60 * 60 * 24);
return Math.round(daysBetween);
}
function formatDate(date){
return date.getDay() + '/' + date.getMonth() + '/' + date.getYear();
}
function searchForPost(event){
let matchingBlogs = [];
event.preventDefault();
const searchQuery = query.value;
blogs.forEach(blog =>{
if(blog.body.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1){
matchingBlogs.push(blog);
}
} )
showBlogs(matchingBlogs.length, matchingBlogs);
}
//show list of blog
function showBlogs(numberOfEntries, blogsToShow = blogs){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
searchButton.addEventListener('click', searchForPost);
showBlogsButton.addEventListener('click', showBlogs);`
HTML CODE
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Youtube - the Blog for Cube puzzlers</h3>
<div class="search-container">
<input type="text" id="searchInput" placeholder="Search for a blog"/>
<button type="button" id="searchButton">Search the blog</button>
</div>
<div id="blog"></div>
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
<button type="button" id="showAllBlogs">Show All Posts</button>
<script src="script.js"></script>
</body>
</html>`

How to display timestamp on a website and terminate a session after a particular time?

So I have this code which displays the current timestamp(IST)
<?php echo date("D M d, Y "); ?> </b>
<body onload="digiclock()">
<div id="txt"></div>
<script>
function digiclock()
{
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
if(s==60)
{
s=0;
m+=1;
}
if(m==60)
{
m=0;
h+=1;
}
if(h==12)
{
h=0;
}
var t=h>=12?'PM':'AM';
document.getElementById('txt').innerHTML=h+":"+m+":"+s+" "+t;
var t=setTimeout(digiclock,500);
}
How to compress this code and how to use it calculate a time limit for terminate a session. For example, a person is playing quiz and the quiz should terminate after 5 minutes and generate the score based on the questions attempted.
Here is example how to use #rckrd's js code snippet with PHP script called by AJAX.
The example is very basic, just to demonstrate implementation logic.
You cann look for live demo here http://demo1.rrsoft.cz/
Download code here http://demo1.rrsoft.cz/test.zip
index.php with HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="startQuiz()">Start timer</button>
<div id="messages"></div>
<div id="timerView"></div>
<div id="quiz_body"></div>
<script src="ajax.js"></script>
</body>
</html>
ajax.js with needed functions (I used #rckrd snippet, because is a grat example how to use it with PHP)
// This function has call php script with quiz answer...
var doAnswer = function(number){
var response_value = $('[name="qr'+number+'"]').val();
var response_message = '"Quiz #' + number + ' has successfuly saved';
$('[name="qr'+number+'"]').prop( "disabled", true );
$.ajax({
url: '/answer.php',
type: 'POST',
async: true,
data: {
quiz: number,
value: response_value
},
success:function(response){
if(response === 'OK'){
$('#messages').html(response_message);
}
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// This function just call the php script to render all quiz questions...
var startQuiz = function(){
$.ajax({
url: '/quiz.php',
type: 'GET',
async: true,
data: {
started: true
},
success:function(response){
$('#quiz_body').html(response);
startTimer();
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// Arange elements over time limit
var gameOver = function(){
$('#header').html('Game over');
$('#list').hide();
}
// This function manage time limitation logic and is called when quiz has started...
var startTimer = function (){
var timeLeftInMillis = 1*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
The quiz.php called by AJAX:
<?php
// very easy list of quizes...
$quiz_template = '
<h1 id="header">Quiz started!</h1>
<ul id="list">
<li>
Quiz 1 text
<input type="text" name="qr1" size="5"/>
<button id="bt1" onclick="doAnswer(1)">Send answer</button>
</li>
<li>
Quiz 2 text
<input type="text" name="qr2" size="5"/>
<button id="bt2" onclick="doAnswer(2)">Send answer</button>
</li>
<li>
Quiz 3 text
<input type="text" name="qr3" size="5"/>
<button id="bt3" onclick="doAnswer(3)">Send answer</button>
</li>
<li>
Quiz 4 text
<input type="text" name="qr4" size="5"/>
<button id="bt4" onclick="doAnswer(4)">Send answer</button>
</li>
<li>
Quiz 5 text
<input type="text" name="qr5" size="5"/>
<button id="bt5" onclick="doAnswer(5)">Send answer</button>
</li>
</ul>
';
// ... and return it
if((bool) $_GET['started'] === true){
die($quiz_template);
}
And Finaly answer.php
<?php
if($_POST){
// grab all needed posted variables... THIS IS JUST FOR DEMO, BECAUSE IS UNSECURED
$quizNumber = $_POST['quiz'];
$quirAnswer = $_POST['value'];
// do quiz PHP logic here, save answer to DB etc...
// when php script runs without errors, just return OK
$error = false;
if($error === false){
die('OK');
}else{
die($someErrorMessage);
}
}
var gameOver = function(){
document.getElementById("timerView").innerHTML = 'Game over';
}
var startTimer = function (){
var timeLeftInMillis = 5*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
<button onclick="startTimer()">Start timer</button>
<div id="timerView"></div>
If you are open to use third part libraries then check out EasyTimer.js plugin, this will solve the issue.
https://albert-gonzalez.github.io/easytimer.js/
or
countdownjs: http://countdownjs.org/demo.html
This is impossible in php, the best way is use JavaScript/Ajax...

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>

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.

Is it possible to use another button to tell me the last alert?

I am looking to have two buttons and one auto generates a random string in an alert and I want another user to be able to go and enter the code in a text box and tell them if its valid or not.
First is this possible? Second, for someone new to JavaScript is this difficult?
Here is the current code I am using right now.
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 5;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
</script>
<script>
function myFunction()
{
alert(randomString());
}
</script>
Thanks1
how about that one:
----------- file: index.html -----------
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Captcha Test</title>
<script src="test.js"></script>
</head>
<body onload="loadCaptcha('captcha-region')">
<div id="captcha-region"
style="text-indent: 10px; background: #fffccc"></div>
<label for="captcha"> Re-type text: </label>
<input id="captcha" type="text" value="" />
<input type="button" value="Submit"
onclick="checkCaptcha('result-region')" />
<input type="button" value="Reload"
onclick="loadCaptcha('captcha-region')" />
<div id="result-region"></div>
</body>
</html>
--------- file: test.js -----------------
function randomInt (range) {
return Math.floor(Math.random() * range);
}
function randomPos (s) {
return randomInt(s.length);
}
function randomChar (s) {
return s.charAt(randomPos(s));
}
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
function randomString () {
var s = '',
i = 0;
while (i++ < 5) {
s += randomChar(chars);
}
return s;
}
function htmlInsert (id, htmlData) {
document.getElementById(id).innerHTML = htmlData;
}
var captcha;
function loadCaptcha (captchaRegion) {
captcha = randomString();
htmlInsert(captchaRegion, '<h1>' + captcha + '</h1>');
}
function checkCaptcha (resultRegion) {
var okText = (captcha === document.getElementById('captcha').value)
? '<span style="color: yellowgreen"> ok </span>'
: '<span style="color: orange"> not ok </span>';
htmlInsert(resultRegion, '<h2>Typed text: ' + okText + '</h2>');
}
This basically is kinda captcha demo, maybe that contains some good parts..
You may want to put index.html & test.js in a directory of your liking (no local web server needed), then from inside that directory execute: "firefox index.html" and you're good to go..
What do you think?

Categories

Resources