I am working on cookies.
Description:
Want to change the js file and store it in cookie.
If I click on B2b industry link, page should replace the js file from banking.js to b2b.js and so on...
The above scenario (replacing the js file) is working as expected.
Problem:
But, after loading the script file, I am trying to replace the contents for <h1>, <p> tags from b2b.js file which is not getting effected...
Any help please?
PS: The same is working for CSS file switch
init.js
var Cookies = {
SetCookie: function (c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
},
GetCookie: function (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);
}
}
}
}
// file change
if (Cookies.GetCookie("industryBased") != "") {
setIndustryFile(Cookies.GetCookie("industryBased"));
}
function setIndustryFile(industryFileName) {
document.getElementById("industryScriptFile").src = industryFileName;
Cookies.SetCookie("industryBased", industryFileName, 60);
return false;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="jquery.min.js"></script>
<script id="industryScriptFile" src="banking.js" type="javascript"></script>
<script src="init.js"></script>
</head>
<body>
<h1>What is Lorem Ipsum?</h1>
<ul>
<li><a href="#b2b" onclick="setIndustryFile('b2b.js');return false;")>B2b industry</a></li>
<li><a href="#travel" onclick="setIndustryFile('travel.js');return false;")>Travel industry</a></li>
<li><a href="#healthcare" onclick="setIndustryFile('healthcare.js');return false;")>Healthcare industry</a></li>
</ul>
<p>Lorem Ipsum</p>
Go to Page 2
</body>
</html>
b2b.js
jQuery('h1').html('B2B Industry heading...');
jQuery('p').html('B2B Industry content...');
jQuery('body').css('color', 'red');
Refers to http://browsercookielimits.squawky.net/
I think your each cookies size is over-sized, so the browser not saving them.
Each browser, have different limit size for cookies storage. Make sure your cookies size is not over-sized.
Related
Code I'm using, works great but it doesn't stick when navigating around the site - because it needs to trigger a cookie - is there a way to do that? Here's the entire code I'm using:
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script>
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>
Nathaniel is correct in his comment that JS executes after the page is loaded, so you'll see a noticeable flicker if you apply the style after page load.
However, for the sake of answering your question, you can get/set a cookie with some pretty simple javascript.
function setCookie(name, value, days)
{
var d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
}
function getCookie(name)
{
var cookies = document.cookie.split(";");
for(var i = 0; i < cookies.length; i++)
{
var ck = cookies[i].trim().split("=");
if(ck[0] == name)
return ck[1];
}
return false;
}
Here's an example with your code:
window.onload = function(){
var viewmode = getCookie("viewmode");
if(viewmode)
document.getElementById('pagestyle').setAttribute('href', viewmode);
}
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
setCookie("viewmode", sheet, 30);
}
function setCookie(name, value, days)
{
var d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
}
function getCookie(name)
{
var cookies = document.cookie.split(";");
for(var i = 0; i < cookies.length; i++)
{
var ck = cookies[i].trim().split("=");
if(ck[0] == name)
return ck[1];
}
return false;
}
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>
I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.
Here is the html:
<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
<div class="fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
</div>
</div>
</body>
</html>
Javascript:
function WriteCookies() {
var d = new Date();
var n = document.getElementById('fullscreen-contents').value;
d.setDate(d.getDate() + 1);
document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
}
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 "";
}
function GetCookies() {
document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
}
Any ideas what could be going on? Thanks!
The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead
var text = document.getElementById('fullscreen-contents');
function saveText() {
localStorage.savedText = text.value;
console.log("saved");
}
function getText() {
if (localStorage.savedText) {
text.value = localStorage.savedText;
console.log("loaded");
}
}
Edited: Here is a fiddle
I want to ask the user in my webapp with a drop-down menu which school website they want to open, then save that in a cookie and automatically open that website next time they open the webapp. I'm not good at JS so please explain.
Thank's in advance.
<head>
<script>
<!-- Cookie script -->
</script>
</head>
<body>
<form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit">Välj</button>
</form>
</body>
Update:
<
form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit" onclick="setCookie()">Välj</button>
</form>
<script type="text/javascript" language="javascript">
function setCookie(cookiename, cookievalue, cookieexdays) {
var d = new Date();
d.setTime(d.getTime() + (cookieexdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cookiename+ "=" + cookievalue+ "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename+ "=";
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 "";
}
function checkCookie() {
var school = getCookie("SelectedSchool");
if (school!= "") {
//redirect to user to link
alert("Welcome to the " + school);
} else {
user = prompt("Please choose your name:", "");
if (school != "" && school != null) {
setCookie("SelectedSchool", school, 365);
}
}
}
</script>
To create a cookie use:
document.cookie="key=value";
To get the value of the select use (example in jquery):
var val = $("#class").val();
Save that in the cookie.
Now next time the user logs in read the cookie using:
var x = document.cookie;
and redirect him with:
location.href = "link";
good luck
Try this, These are the JavaScript function which you can use to save, get or check cookie
<head>
<script>
<!-- Cookie script -->
</script>
</head>
<body>
<form>
<select id="class">
<option value="Choose">Choose</option>
<option value="flah">School#1</option> <!-- Should redirect to site #1 -->
<option value="june">School#2</option> <!-- Should redirect to site #2 -->
</select>
<button type="submit">Välj</button>
</form>
<script type="text/javascript" language="javascript">
function setCookie(cookiename, cookievalue, cookieexdays) {
var d = new Date();
d.setTime(d.getTime() + (cookieexdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cookiename+ "=" + cookievalue+ "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename+ "=";
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 "";
}
function checkCookie() {
var school = getCookie("SelectedSchool");
if (school!= "") {
//redirect to user to link
alert("Welcome to the " + school);
} else {
user = prompt("Please choose your name:", "");
if (school != "" && school != null) {
setCookie("SelectedSchool", school, 365);
}
}
}
</script>
</body>
I'm trying to implement cookies for my website, i just wanted to redirect users to a splash page and have a "remember me" checkbox there and once they checked off that and pressed enter, they will not see that page anymore.
So using COOKIE Plugin I can set a cookie for users and redirect them to the page, but I wasn't able to implement how to detect the remember me box..
$(function() {
var COOKIE_NAME = 'splash-page-cookie';
$go = $.cookie(COOKIE_NAME);
if ($go == null) {
$.cookie(COOKIE_NAME, 'test', { path: '/', expires: 6 });
window.location = "/splash.php"
}
else {
}
});
Anybody has done like this before? Or anybody have any similar idea to implement this?
Any help would be appreciated.
Solution #1 (With alert boxes): I came up with this but without the COOKIE Plugin. Hopefully you can get some use out of this. Mostly Pure JS with some JQuery to fancy it up a little.
Here is the DEMO.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
$('#x').text("You're the Best!");
setCookie();
} else {
$('#x').text("Come on, You know you want to!");
}
});
});
function setCookie() {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
addCookie("username", user, 30);
}
}
function addCookie(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;
//window.location.href = "https://www.google.com"; // redirect after the prompt
}
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) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
<p><div id='x'></div></p>
</body>
</html>
Solution #2 (NO alert boxes): I came up with this as a second simplified solution by request which is more compatible with mobile (Chrome, etc.). Hopefully you can get some use out of this. Mostly Pure JS with some JQuery to fancy it up a little.
Here is the DEMO.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
$('#x').text("You're the Best!!!");
addCookie(30);
} else {
$('#x').text("Come on, You know you want to!");
deleteAllCookies();
}
});
});
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
function addCookie(exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = expires;
}
function checkCookie() {
if (document.cookie == false) {
//alert("Welcome New User");
} else if (document.cookie.indexOf("expires") >= 0) {
//alert("Welcome Back");
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
<p><div id='x'></div></p>
</body>
</html>
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to enable cookies
The readCookie is right under the greetUser function. I put in the writeCookie function but it causes the alert boxes not to show. So I commented it out.
This is about the cookies not working. I'm suppose to sort the username it a variable so that iRock will remember the name and use it in the prompt.
It seems like the last part of the code works because I get the alert boxes, but I don't get the first and second alert boxes. The page is suppose to open in an alert box saying, "Hello, I am a pet rock." but it doesn't.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>iRock - The Virtual Pet Rock</title>
<link href="donut_stylesheet/donut.css" rel="stylesheet" type="text/css" />
<script type ="text/javascript">
var userName;
function resizeRock(){
document.getElementById("rockImg").style.height = (document.body.clientHeight - 100) * 0.9;
}
function greetUser(){
userName = readCookie("rock_username");
if(userName)
alert("Hello " + userName + ", I missed you.");
else
alert("Hello, I am your pet rock");
}
function touchRock(){
if(userName)
alert("I like attention," + userName + ". Thank you.");
}
userName = prompt("What is your name?", "Enter name here.");
if(userName)
alert("It is good to meet you, " + userName + ".");
//writeCookie(irock_username", userName, 1 * 365);
document.getElementById("rockImg").src = "rock_happy.png";
setTimeout("document.getElementById(('rockImg').src = 'images/rock.png';", 5 * 60 * 1000);
</script>
</head>
<body onload="resizeRock(); greetUser(); onResize="resizeRock();">
<img id="rockImg" src="images/rock.png" alt="iRock" style="cursor:pointer" onClick="touchRock();" />
</body>
</html>
There are no built in readCookie or writeCookie functions in JavaScript. You will have to supply your own, like this.
function writeCookie(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);
}