CSS Stylesheet Switching via adding cookies - javascript

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>

Related

Display message after countdown

I have currently created a countdown timer using javascript. I want to display a message right after the countdown finishes. So, how do I display that text message if the countdown finishes?
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = true;
if((new Date()) > ts){
// The new year is here! Count towards something else.
// Notice the *1000 at the end - time must be in milliseconds
ts = (new Date()).getTime() + 24*60*60*1000;
newYear = false;
}
$('#countdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
var message = "";
message += hours + " jam ";
message += minutes + " minit" + " dan ";
message += seconds + " saat" + " lagi!";
note.html(message);
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="assets/css/styles.css" />
<link rel="stylesheet" href="assets/countdown/jquery.countdown.css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="continer">
<p><span id="timer"></span></p>
</div>
<center><img class="title" src="title.svg"></center>
<img class="icon1" src="icon1.svg">
<img class="icon2" src="icon2.svg">
<div id="countdown"></div>
<p id="note"></p>
<!-- JavaScript includes -->
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="assets/countdown/jquery.countdown.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
Below is the code that I used
Well you can use setInterval, clearInterval and use a counter to keep track of seconds passed
function myFunction() {
var seconds = 0;
var finiteNumber = 300; // any number which can be calculated
var interval = setInterval(function(){
seconds++;
if(seconds === finiteNumber) {
console.log(seconds);
clearInterval(interval )
}
}, 1000);
}
You should use setTimeout as it will automatically stop on one successful execution.
function myFunction() {
var myTimeInSeconds = 600;
setTimeout(function(){
console.log(seconds);
alert('Success');
document.getElementById("demo").innerHTML = "Success Message!";
}, myTimeInSeconds);
}

Cookies - js file data is not updating dynamically

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.

Javascript cookie not saving when user input reaches a certain size

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

Don't show this page anymore (JQUERY cookie)

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>

JavaScript clock (timer) to start from the provided time span stored in asp hidden field

<html>
<head>
<title>Digital clock</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<link href="../Styles/jquery.alerts.css" rel="stylesheet" type="text/css" />
<script src="../Scripts/jquery.alerts.js" type="text/javascript"></script>
</head>
<body onunload="return returnTime()" >
<script language="JavaScript" type="text/javascript">
function returnTime() {
var closeTime = new Date();
window.returnValue = closeTime;
}
function CloseWindow() {
window.close();
}
</script>
<body onload="timer()" >
<style type="text/css">
#time{
font-size:50pt;
}
#body
{
background-color:#F3F3F3;
}
</style>
<script type="text/javascript">
var digiclock = "00:00:00";
i = 0;
function timer() {
var digiformat = "";
if (i > 3599) {
var H = Math.floor(i / 3600);
}
else {
var H = 0;
}
var M = i - (H * 3600)
if (M > 59) {
M = Math.floor(M / 60)
}
else {
M = 0
}
var S = i - (M * 60)
if (H < 10) {
H = "0" + H;
}
if (M < 10) {
M = "0" + M;
}
if (S < 10) {
S = "0" + S;
}
document.getElementById('time').innerHTML = H + ":" + M + ":" + S;
setTimeout('timer()', 1000);
i++;
}
</script>
<table style="background-color:#F3F3F3;">
<tr>
<td><div><center><p style="font-family:Calibri;font-size:1.8em;color:#104E8B;">Total Elapsed Time</p> </center></div>
</td>
</tr>
<tr>
<td><div id="time"><center>90</center></div>
</td>
</tr>
<tr>
<td>
<center>
<form runat="server">
<asp:Button ID="btnStop" runat="server" Text="Stop"
style="width:150px;height:30px;font-weight:bold;background-color:#104E8B;color:White;border:1px solid"
onclick="btnStop_Click" /></form></center>
<input id="HiddenTaskname" type="hidden" value="" runat="server" />
</td>
</tr>
</table>
</body>
Above you can see that when the above page opens a timer(Clock) is starting from 00:00:00 .
I want to update it in such a way that it will start from the specified time as mentioned .
For example if we pass an argument to this page as 14:30:58 then the timer will start from 14:30:58 and so on.
I ll pass this argument from the query string and storing it in an asp hidden field in this page .Please help me to update above code so that it fulfills my requirement.
var digiclock = "<%= Request.QueryString["QueryStringVariableName"] %>";
Should work, Haven't tested it, you might need to change the double quotes to single. I'm not a pro so play with it.

Categories