I am a web design newb so I am not sure if this is the best forum or if there's some blindingly obvious solution that completely eludes me. So forgive me if either is the case.
So, here's the deal.
I am building a blog using craft cms and on my layout file I am using a styleswitcher.js script to switch between two css files.
<head>
<link rel="stylesheet" type="text/css" media="screen" href="http://www.example.com/weblog1.css"/>
<link rel="stylesheet" type="text/css" media="screen" title="aeroplaniko" href="http://www.example.com/weblog1.css"/>
<link rel="alternate stylesheet" type="text/css" media="screen" title="white" href="http://www.example.com/weblog3.css" />
<script type="text/javascript" src="http://www.example.com/jquery-1.12.1.min.js" ></script>
<script type="text/javascript" src="http://www.example.com/styleswitcher.js">
</head>
<body>
</body>
I am also using css styles in order to deploy social media icons. So for example, facebook looks like this:
.facebook {
margin-right: 2px;
width: 28px;
height: 28px;
display:inline-block;
background-repeat:no-repeat;
background-image: url('logos/facebook.png');
background-size:28px 28px;
background-position:center bottom;
}
.facebook:hover {
background-image: url('logos/facebookhover.png');
}
Once I noticed that Internet Explorer is bad at displaying png files, I decided to switch to svg files. After some work, I was able to convert my png files to svg. I also changed all the png files referenced on my stylesheets to svg.
Here's the problem however. As soon as I use the css stylesheets which include the svg files, switching between styles only affects the particular page in which I made the switch and not the whole site.
So if I switch styles on the main page and then I go to an article page, I see the previous stylesheet. Sometimes, the style changes even when I go through paginated pages.
So, what's wrong and how can I fix it?
PS. I should note that I noticed the same problem even with png files when I was testing my website on my ipad.
PS2. Ok, here's the code in the styleswitcher.js file:
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);
Related
I'm working on a art project about poetry, writing processes and A.I (you can see the ongoing tests here http://82.223.18.239/writing3.php) and I would like to implement a thing I saw on some other website, for exemple here constantdullaart.com/
For exemple I have now : http://82.223.18.239/writing3.php (this is a temporary URL) and I would like to expend the writing to the url box (The after domain part of course). A short looped text could be constantly writen there, or a serie of symbols like on Dullaart website.
I know it can sound technically messy and not elegant at all but, still do you have any idea how to do it ?
Here's our actual code
<head>
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
#myTable{
width:"90%";
height:"100%";
overflow:hidden;
min-width:250px;
white-space: pre-wrap;
word-wrap:break-word;
position:absolute;
border:solid 0px;
top:-500px;
left:320px;
right:320px;
bottom:0px;
font-size:100px;
font-family:"Times New Roman", Times, serif;
text-align:left
}
#body{
height:"100%";
overflow:auto;
min-width:250px;
}
::-webkit-scrollbar {display: none;}
</style>
</head>
<body>
<div id="myTable"> <div>
<script type="text/javascript">
var skip = 0;
function get_data(index) {
$.ajax({
url : 'getData.php',
type : 'POST',
data: ({"skip":skip}),
success : function(data) {
if(data && data.trim()!='') {
skip = skip+1;
showText("#myTable", data, 0, 20);
}
else {
setTimeout(function () { get_data(skip); }, 30000);
}
},
error : function(request,error)
{
alert("Request error : "+JSON.stringify(request));
}
});
}
function showText(target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
$('#myTable').css('overflow', 'hidden').bind('DOMNodeInserted', function () {
this.scrollTop = this.scrollHeight;
});
}
else {
get_data(skip);
$('#myTable').css('overflow', 'scroll')
}
}
//var period = 10000; //NOTE: period is passed in milliseconds
get_data(skip);
//setInterval(page_refresh, period);
</script>
</body>
This whole function and piece of code can be found in the page source. In Google chrome or your favorite web browser right click and select "view page source". You will find this function which does what you want:
<SCRIPT LANGUAGE="JavaScript">
var message = new Array();
message[0] = ""
var reps = 2;
var speed = 666;
var p = message.length;
var T = "";
var C = 0;
var mC = 0;
var s = 0;
var sT = null;
if (reps < 1) reps = 1;
function doIt() {
T = message[mC];
A();
}
function A() {
s++;
if (s > 8) { s = 1;}
if (s == 1) { document.title = 'βπ»ββπΌββπ½ββπΎββπΏββπ»ββπΌβββπ»ββπΌββπ½ββπΎ'+T+'βπ»ββπΌββπ½ββπΎββπΏββπ»ββπΌββπ½ββπΎββ'; }
if (s == 2) { document.title = 'β οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ '+T+'β οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈβ οΈ'; }
if (s == 3) { document.title = 'πππππππππππππππππππππ'+T+'βπ»ββπΌββπ½ββπΎββπΏββπ»ββπΌββ'; }
if (s == 4) { document.title = 'βπ»ββπΌββπ½ββπΎββπΏββπ»ββπΌββπ½ββπΎββ'+T+'ββββββββββββββββββββ'; }
if (s == 5) { document.title = 'πππππππππππππππππππ'+T+'π π π π π π π π π π π π π π π π π π π π '; }
if (s == 6) { document.title = 'π£π£π£π£π£π£π£π£π£π£π£π£π£π£π£π£π£π£π£π£'+T+'πππΏπππΌππΎππΌππΏπππΌππΎπππΏπππΌππΎππΌ'; }
if (s == 7) { document.title = 'ππππππππππππππππππ'+T+'ππππππππππππππππππ'; }
if (s == 8) { document.title = 'βπ»ββπΌββπ½ββπΎββπΏββπ»ββπΌββπ½ββπΎββπΏ'+T+'β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³β³'; }if (C < (8 * reps)) {
sT = setTimeout("A()", speed);
C++;
}
else {
C = 0;
s = 0;
mC++;
if(mC > p - 1) mC = 0;
sT = null;
doIt();
}
}
doIt();
(function() {
var template = 'ββββββ βββββ³ββ ββββ³β βββββπ£βπΎ'.split(''),
len = template.length,
chars, string, i, j, k,
pushOrHash = typeof window.history.pushState === 'function',
increase = function(n) {
return n < len - 1 ? n + 1 : 0;
},
update = function() {
chars = [];
j = k;
for (i=0; i<len; i++) {
j = increase(j);
chars[i] = template[j];
}
string = ['/', chars.join(''), '/'].join('');
k = increase(k);
if (pushOrHash) {
window.history.pushState(null, null, string);
} else {
window.document.location.hash = string;
}
setTimeout(update, 1000);
};
update();
})();
</script>
<script type="text/javascript">
function pageLoad()
{
alert('The image of external things possesses for us the ambiguous dimension that in external nature everything can be considered to be connected, but also as separated. The uninterrupted transformations of materials as well as energies brings everything into relationship with everything else and make one cosmos out of all the individual elements. On the other hand, however, the objects remain banished in the merciless separation of space; no particle of matter can share its space with another and a real unity of the diverse does not exist in spatial terms. And, by virtue of this equal demand on self-excluding concepts, natural existence seems to resist any application of them at all. Only to humanity, in contrast to nature, has the right to connect and separate been granted, and in the distinctive manner that one of these activities is always the presupposition of the other. By choosing two items from the undisturbed store of natural things in order to designate them as -separate-, we have already related them to one another in our consciousness, we have emphasized these two together against whatever lies between them. And conversely, we can only sense those things to be related which we have previously somehow isolated from one another; things must first be separated from one another in order to be together. Practically as well as logically, it would be meaningless to connect that which was not separated, and indeed that which also remains separated in some sense. The formula according to which both types of activity come together in human undertakings, whether the connectedness or the separation is felt to be what was naturally ordained and the respective alternative is felt to be our task, is something which can guide all our activity. In the immediate as well as the symbolic sense, in the physical as well as the intellectual sense, we are at any moment those who separate the connected or connect the separate. Georg Simmel from -Bridges and Doors- 1909ΜΏ');
}
pageLoad();
</script>
I'm building a website template for primarily text content.
I would like to have two user switchable color schemes.
One dark background/light text and one light background/dark text to suit different viewing conditions.
How do I plan and design it such that user can toggle color scheme with a click of button and have cookie memorize the user's preference?
Without breaking the design, I would also like to let the user be able to increase the font-size and line-height for certain content block, eg. <div id="article"></font>
Is this feasible?
#GamerNebulae #EliTownsend After studying the answer and making some modification, I come up with a solution that works for my situation.
Not sure if it's heavy when it comes to execution. Any advice for further improvement is appreciated.
CSS
body.dark {
background: #222;
color: #777;
}
HTML
Switch
Javscript
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function changeTheme() {
if (jQuery("body").hasClass("dark")) {
jQuery("body").removeClass("dark");
createCookie('theme', 'regular', 7);
}
else {
jQuery("body").addClass("dark");
createCookie('theme', 'dark', 7);
}
}
// initialize page, apply theme color by checking cookie variable 'theme'
var theme = readCookie('theme');
if(theme == "dark") jQuery("body").addClass("dark");
else if (theme == "regular") jQuery("body").removeClass("dark");
else if (jQuery("body").hasClass("dark")) createCookie('theme', 'dark', 7);
Stylesheets
<link rel="stylesheet" type="text/css" title="blue" href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink" href="http://example.com/css/pink.css">
HTML
<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>
Javascript
//TO BE CUSTOMISED
var style_cookie_name = "style" ;
var style_cookie_duration = 30 ;
var style_domain = "thesitewizard.com" ;
// END OF CUSTOMISABLE SECTION
// You do not need to customise anything below this line
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, style_domain );
}
}
function set_style_from_cookie()
{
var css_title = get_cookie( style_cookie_name );
if (css_title.length) {
switch_style( css_title );
}
}
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
// 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 )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var cookie_string = document.cookie ;
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (
'(^|;)[\s]*' +
cookie_name +
'=([^;]*)' );
return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
I found this located here How to Use Javascript to Change a CSS
This is my website http://natjecanje.interes.hr/
I want to have big A and small A and by pressing one of this "A" people can change all letters size on website, all elements need change font size, Thank you! :)
P.S. I did google search, but i didn't find what i was looking for.
You need to use 2 differents CCS Style, a little JS script
Please Find below Javascript :
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
if (navigator.appName == "Microsoft Internet Explorer") {
window.resizeBy(0,-10);
window.resizeBy(0,+10);
}
}
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);
You can save this script in a fil named : changement_css.js
Now you need a first CCS style whit regular font-size, and another one with a different font size, and include it in your HTML file.
<!--Default CSS-->
<link rel="stylesheet" type="text/css" href="normal.css" title="normal">
<!--Alternate CSS-->
<link rel="alternate stylesheet" type="text/css" href="grand.css" title="grand">
Copy those line instead of your regular CSS
Then, use this code to call your JS after your CSS link :
<script language="JavaScript" src="changement_css.js" type="text/javascript"></script>
Then, you need a button to change font-size :
<ul>
<li>Normal</li>
<li>Grand</li>
</ul>
I hope this could help you.
This message is translate from : http://forum.alsacreations.com/topic-6-11551-1-Boutons-AugmenterDiminuer-la-Taille-du-Texte-.html
function promjenaVelicineFonta(inc)
{
var p = document.getElementsByTagName('p');
for(n=0; n<p.length; n++) {
if(p[n].style.fontSize) {
var size = parseInt(p[n].style.fontSize.replace("px", ""));
} else {
var size = 14;
}
p[n].style.fontSize = size+inc + 'px';
}
var span = document.getElementsByTagName('span');
for(n=0; n<span.length; n++) {
if(span[n].style.fontSize) {
var size = parseInt(span[n].style.fontSize.replace("px", ""));
} else {
var size = 14;
}
span[n].style.fontSize = size+inc + 'px';
}
}
I found a solution, here it is.
Do you mean font size (i.e. 10pt, 12pt etc) or font capitalisation (i.e. a or A)? I think you mean capitalisation based on the theme of your question (because you said 'big' and 'small')?
You can control capitalisation with CSS via the 'text-transform' property (http://www.w3schools.com/cssref/pr_text_text-transform.asp).
You can use JavaScript to add remove CSS classes which is outlined in this thread: Change an element's class with JavaScript
Using this approach you could add remove CSS classes which use text-transform to change the capitalisation of the font.
I am using a background switcher so far compiled from a few examples and tutorials I have found around, it consists of a stylesheet and a few child classes that each contain a different background image; when the switcher image is clicked, the javascript sequentially toggles the next body class in order and writes a new value to the cookie. Everything works okay except for the cookie loading upon page load. If I refresh the page, the cookie does not recall, and thus the body class does not default to the last selected class. Here is the code
Here is a jsfiddle of it: http://jsfiddle.net/Lse3V/2/
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="background switcha" />
<meta name="keywords" content="" />
<title>background switcha</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="head.js"></script>
<script type="text/javascript">head.js( "jquery.js","back.js", function() { });</script>
</head>
<body class="orig">
</body>
</html>
style.css
body.green{background: #3F0 url(background1.jpg) center top fixed repeat}
body.blue{background: #00F url(background2.jpg) center -80px fixed repeat}
body.red{background: #F00 url(background3.jpg) center top fixed repeat}
body.grey,html{background: #666 url(background4.jpg) repeat}
body{min-height:800px}
#backgroundswap{display:block;display:inline-block;zoom:1;width:101px;height:22px;background-image:url(backgroundswap.png);background-repeat:no-repeat;margin-bottom:12px;}
body.green #backgroundswap{background-position:center bottom}
body.blue #backgroundswap{background-position:0 -66px}
body.red #backgroundswap{background-position:0 -44px}
body.grey #backgroundswap{background-position:0 -22px}
body.orig{background-position:0 0}
body.orig{
background: #FF0 url(background5.jpg) center top fixed repeat
}
back.js
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
$(document).ready(function(){
//Switch backgrounds and create the cookie...
$("#backgroundswap").click(function(){
var old_bg = ["green","blue","red","grey","orig"];
var new_bg = ["blue","red","grey","orig","green"];
var currentClass = $('body').attr("class");
if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]===obj){ return i; } } return -1; } }
$('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);
$.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });
});
});
head.js
(function(a){var b=a.documentElement,c=navigator.userAgent.toLowerCase().indexOf("msie")!=-1,d=false,e=[],f={},g={},h=a.createElement("script").async===true||"MozAppearance"in a.documentElement.style||window.opera;var i=window.head_conf&&head_conf.head||"head",j=window[i]=window[i]||function(){j.ready.apply(null,arguments)};var k=0,l=1,m=2,n=3;h?j.js=function(){var a=arguments,b=a[a.length-1],c=[];r(b)||(b=null),q(a,function(d,e){d!=b&&(d=p(d),c.push(d),v(d,b&&e==a.length-2?function(){s(c)&&b()}:null))});return j}:j.js=function(){var a=arguments,b=[].slice.call(a,1),c=b[0];if(!d){e.push(function(){j.js.apply(null,a)});return j}c?(q(b,function(a){r(a)||u(p(a))}),v(p(a[0]),r(c)?c:function(){j.js.apply(null,b)})):v(p(a[0]));return j},j.ready=function(a,b){r(a)&&(b=a,a="ALL");var c=g[a];if(c&&c.state==n||a=="ALL"&&s()){b();return j}var d=f[a];d?d.push(b):d=f[a]=[b];return j};function o(a){var b=a.split("/"),c=b[b.length-1],d=c.indexOf("?");return d!=-1?c.substring(0,d):c}function p(a){var b;if(typeof a=="object")for(var c in a)a[c]&&(b={name:c,url:a[c]});else b={name:o(a),url:a};var d=g[b.name];if(d)return d;for(var e in g)if(g[e].url==b.url)return g[e];g[b.name]=b;return b}function q(a,b){if(a){typeof a=="object"&&(a=[].slice.call(a));for(var c=0;c<a.length;c++)b.call(a,a[c],c)}}function r(a){return Object.prototype.toString.call(a)=="[object Function]"}function s(a){a=a||g;for(var b in a)if(a[b].state!=n)return false;return true}function t(a){a.state=k,q(a.onpreload,function(a){a.call()})}function u(a,b){a.state||(a.state=l,a.onpreload=[],w({src:a.url,type:"cache"},function(){t(a)}))}function v(a,b){if(a.state==n&&b)return b();if(a.state==m)return j.ready(a.name,b);if(a.state==l)return a.onpreload.push(function(){v(a,b)});a.state=m,w(a.url,function(){a.state=n,b&&b(),q(f[a.name],function(a){a()}),s()&&q(f.ALL,function(a){a.done||a(),a.done=true})})}function w(c,d){var e=a.createElement("script");e.type="text/"+(c.type||"javascript"),e.src=c.src||c,e.async=false,e.onreadystatechange=e.onload=function(){var a=e.readyState;!d.done&&(!a||/loaded|complete/.test(a))&&(d(),d.done=true)},b.appendChild(e)}setTimeout(function(){d=true,q(e,function(a){a()})},300),!a.readyState&&a.addEventListener&&(a.readyState="loading",a.addEventListener("DOMContentLoaded",handler=function(){a.removeEventListener("DOMContentLoaded",handler,false),a.readyState="complete"},false))})(document)
You are setting the cookie great, but there's nothing to check whether it's set or act on it if it does detect it. This bit of code will do just that for ya.
if($.cookie('backswap')) {
$('body').removeClass().addClass(old_bg[$.cookie('backswap')]);
};
There's some other minor adjustments to ensure the arrays are scoped for everything, so here's the entire chunk of code that's affected.
$(document).ready(function(){
window.new_bg = ["blue","red","grey","orig","green"];
window.old_bg = ["green","blue","red","grey","orig"];
if($.cookie('backswap')) {
$('body').removeClass().addClass(old_bg[$.cookie('backswap')]);
};
//Switch backgrounds and create the cookie...
$("#backgroundswap").click(function(){
currentClass = $('body').attr("class");
$('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);
$.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });
});
});
Hope this helps!
How to switch an image when the page refreshes, using Javascript?
Let's say I have 2 images:
ImageA.jpg
ImageB.jpg
I want to switch those images at locationA and locationB when the page is refreshed.
Simulation:
- Page Refresh #1
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>
- Page Refresh #2
<img id='locationA' src='ImageB.jpg'>
<img id='locationB ' src='ImageA.jpg'>
- Page Refresh #3
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>
[Update #1]
I try this implementation, but it doesn't work. Could anyone tell me whats wrong with this code?
<html>
<head>
<script type="text/javascript">
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = sessionStorage.getItem('index');
if(index) index = 0;
if(index==0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index==1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
sessionStorage.setItem('index', index);
</script>
</head>
<body>
<img id='locationA' src=''>
<img id='locationB' src=''>
</body>
</html>
[Update #2]
Tested on:
FF 16.0.1 --> Working!
IE 8 --> doesn't work
Here is the code:
<html>
<head>
<script type="text/javascript">
function switchImage()
{
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = sessionStorage.getItem('index');
if(index == null) index = 0;//set index to zero if null
index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.
if(index == 0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index == 1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
sessionStorage.setItem('index', index);
}
</script>
</head>
<body onload="switchImage()">
<img id='locationA' src='src_locationA'>
<img id='locationB' src='src_locationB'>
</body>
</html>
Thanks to Jack for the
clue! and thanks to Jon Kartago
Lamida for
the sample!
Thanks.
Set a flag variable in your cookie ( Check Javascript Cookie SO Question for setting a cookie ).
Every time the page loads, ( in your onload function ) check the value of the flag.
Say if value is 0 . Show ImageA in LocationA. Then invert the flag value to 1.
Else if value is 1 . Show ImageB in LocationA. Then invert the flag value to 0.
The flag value will be stored in your cookie.
Hope this helps,
Shoubhik
I try to give example according to Jack, using localStorage. Most modern browser have support this. I haven't this this code yet, but more or less should be like this.
<html>
<head>
<script type="text/javascript">
function init(){
var imageA = 'imageA.jpg';
var imageB = 'imageB.jpg';
// state maintaned using localStorage
var toggle = localStorage.getItem('toggle');
if(toggle) toggle = "A"; // if no state yet, initialize
if(toggle == "A"){
toggle = "B";
document.getElementById('locationA').src=imageA;
document.getElementById('locationB').src=imageB;
}else{
toggle = "A";
document.getElementById('locationA').src=imageB;
document.getElementById('locationB').src=imageA;
}
// put state back to local storage
localStorage.setItem('toggle', toggle);
}
</script>
</head>
<body onload="init()">
<img id='locationA' src=''>
<img id='locationB' src=''>
</body>
</html>
Base on Damien_The_Unbeliever comment I create this answer post for my own question.
This is final working solution that I use.
[Update #3]
Tested on:
FF 16.0.1 --> Working!
IE 8 --> Working!
Chrome 24 --> Working! (Note: this browser need a little extra effort to make it can read cookie. see this link)
Basically the code is still same as Update #2, the different is I use cookie instead of sessionStorage. Here is the complete code:
<html>
<head>
<script type="text/javascript">
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function switchImage()
{
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = readCookie('index'); //sessionStorage.getItem('index');
if(index == null) index = 0;//set index to zero if null
index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.
if(index == 0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index == 1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
createCookie('index', index); //sessionStorage.setItem('index', index);
}
</script>
</head>
<body onload="switchImage()">
<img id='locationA' src='src_locationA'>
<img id='locationB' src='src_locationB'>
</body>
</html>