alternate css files set selection NEW QST [duplicate] - javascript

This question already has answers here:
How do I switch my CSS stylesheet using jQuery?
(5 answers)
Closed 8 years ago.
THIS QµUESTION HAS NOT HAD AN ANSWER YET (WRONG TAGGING)
I would like to give the user the ability to choose between different styles (CSS).
Do make sure you read the bold characters before answering (I know very simla questions have been asked but this one is DIFFERENT ;-)
Here is why:
** I cannot alter the original HTML files** (because they are too numerous and produced by a programme that creates mini websites, with tons of small pages, all more or less on the same canvas)
The pages all refer to a css file like so:
h r e f="http://...mypage1.css" type="text/css" rel="stylesheet"
but there is no "id".
I have read, on this site, of possibilities to switch from one css address to another,by grabbing the id (in JS) and changing its's url.
But is there any possibility without altering the HTML?
Thanks

There's a great example of this on CSS Tricks. Here's the demo, download the code example and take a peek. It uses javascript to switch.
Here's the jist of it:
HTML HEAD
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="alternate stylesheet" type="text/css" href="stylealt1.css" title="alternate 1" />
<link rel="alternate stylesheet" type="text/css" href="stylealt2.css" title="alternate 2" />
<script>
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);
</script>
HTML BODY
<img src="defaultstyle.jpg" alt="default style" />
<img src="altstyle1.jpg" alt="alternate style 1" />
<img src="altstyle2.jpg" alt="alternate style 2" />

Related

how to save toogle class with cookies? or help me with something similar/alternative to this one

function myFunction() {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
{
var x = document.getElementById("hs");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the class names</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<div>
<div id="sh" class="sh">dark black</div>
<div id="hs" class="hs">light white</div>
</div>
i want it's class to be saved so when i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same. Thanks for Reading This. :)
You can use local storage. Its very simple and better than cookies.
for example to set element bg color (on load):
if(localStorage.getItem("color") == "black") {
element.classList.add("dark"); }
and on your function add :
localStorage.setItem("color",black or white )
Note: You should add an if statement on your function to check if class available set local storage item is set to black or not
add this to end of jquery file (Mrbg => mr babak golbaharan :) )
$.extend({
MrbgSetCookie:function(name,value,days){
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
},
MrbgGetCookie:function(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;
},
MrbgRemoveCookie:function(name){
document.cookie = name+'=; Max-Age=-99999999;';
},
});
now you can use this for set, get and remove cookies
such as this
$.MrbgSetCookie( 'cookieName', 'cookieValue' , 'period in day' );
in this case:
element = document.getElementById("body");
element.classList.toggle("bdark");
( element.classList.contains('bdark') )?
$.MrbgSetCookie( yourElementID, 'bdark' , 365 ):
$.MrbgRemoveCookie(yourElementID );

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>

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-->

How to use JavaScript to change a cascading style sheet dynamically

I found a site that can change css dynamically using JavaScript http://www.thesitewizard.com/javascripts/change-style-sheets.shtml
like it will have 2 css and you're able to click one of them and change the design of the whole site. But my problem is that for example I changed it into an alternate css then reload it it will jsut change back into the original css. What can I do to make it stay as the css that I chose?
This is the JavaScript
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 "";
}
// *** TO BE CUSTOMISED ***
var style_cookie_name = "theme" ;
var style_cookie_duration = 30 ;
// *** END OF CUSTOMISABLE SECTION ***
function switch_style ( css_title )
{
// You may use this script on your site free of charge provided
// you do not remove this notice or the URL below. Script from
// http://www.thesitewizard.com/javascripts/change-style-sheets.shtml
var i, link_tag ;
for (i = 0, link_tag = document.getElementsByTagName("link") ;
i < link_tag.length ; i++ ) {
if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) &&
link_tag[i].title) {
link_tag[i].disabled = true ;
if (link_tag[i].title == css_title) {
link_tag[i].disabled = false ;
}
}
set_cookie( style_cookie_name, css_title,
style_cookie_duration );
}
}
function set_style_from_cookie()
{
var css_title = getCookie( style_cookie_name );
alert(css_title);
if (css_title.length) {
switch_style( css_title );
}
}
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
alert(cookie_value)
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
function get_cookie ( cookie_name )
{
var cookie_string = document.cookie ;
alert(cookie_string)
var re = new RegExp("(^|;)[\s]*" + cookie_name + "=([^;]*)");
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (re);
alert(cookie_value)
return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
set_style_from_cookie()
css
<link rel="stylesheet" type="text/css" title="blue"
href="http://myanimesekai.com/css/newcss.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
href="http://myanimesekai.com/css/css.css">
this is the form
<form>
<input type="submit"
onclick="switch_style('blue');return false;"
name="theme" value="Blue Theme" id="blue">
<input type="submit"
onclick="switch_style('pink');return false;"
name="theme" value="Pink Theme" id="pink">
</form>
it says that I have to put the right info on the set cookie part
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
so I changed it into
function set_cookie ( "style", "theme",
7, "myanimesekai.com" )
but what happen is that it will not work If I changed it into that. All I want is that if the user picked a style it will stay as that even when he/she reload the page OR go to another page of my site
I already included this part:
<body onload="set_style_from_cookie()">
but it still doesn't work.
fiddle: http://jsfiddle.net/SALgL/
you seem to change the function itself rather than "calling" the function. revert back the set_cookie function as it was with parameters and just change the variables at the top:
var style_cookie_name = "theme" ;
var style_cookie_duration = 7 ;
also the regex used in get_cookie is malformed and is not working use this function instead:
function get_cookie(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 "";
}

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