CSS body class jquery switcher with cookies - javascript

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!

Related

Styleswitcher.js and svg

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

White space on layer update in 360 degree viewer - Leaflet

Good afternoon everyone!
I am trying to build a 360 degree viewer with zoom control. For that, I´m usig Leaflet. Everything works fine but layer update.
To change folder´s image container, I´m updating layer´s url, but in this change a white space appears for a while (few ms). I´ve been looking on Leaflet docs, internet, and trying on my own, but i´m unable to solve this.
Does anyone know any possible solution?
Thanks everyone for helping me!
PD: I can´t also give you images, but ím working with TileLayers.
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Untitled Document</title>
<link href="style/jquery-ui.css"rel="stylesheet"/>
<link href="style/bootstrap.css" rel="stylesheet">
<link href="style/main.css" rel="stylesheet">
<link href="http://cdn.leafletjs.com/leaflet-0.7.4/leaflet.css" rel="stylesheet" />
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<img src="img norman foster/header.PNG" id="img_header" />
<div class="threesixty visor" id="image-map"></div>
<div id="slider"></div>
<div class="buttons">
<a class="btn custom_previous"><img src="src/images/rotateleftbutton.png" class="img-responsive" alt="Girar hacia la izquierda" /></a>
<a class="btn custom_next"><img src="src/images/rotaterightbutton.png" class="img-responsive" alt="Girar hacia la derecha" /></a>
</div>
<img src="img norman foster/footer.PNG" id="img_footer" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.4/leaflet.js"></script>
<script src="js/L.TileLayer.Zoomify.js"></script>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
window.onload = init;
var map = "";
var layer = "";
var oldSrc = "";
var newSrc = "";
var gui = "";
var path = "";
var imgcounter = 1;
var extension = "_img/";
var layers = new Array(80);
function init() {
oldSrc = './360/TNFF_0PO6055M_001/TNFF_0PO6055M_001-001_img/';
gui = oldSrc.indexOf("-");
path = oldSrc.substr(0, gui + 1);
getFiles();
//SLIDER
$(function() {
$("#slider").slider({
range : "min",
value : 1,
min : 1,
max : 80,
slide : function(event, ui) {
var photonumber = ui.value;
if (photonumber >= 1 && photonumber < 10) {
photonumber = "00" + String(photonumber);
newSrc = path + String(photonumber) + extension;
} else {
newSrc = path + "0" + String(photonumber) + extension;
}
oldSrc = newSrc;
imgcounter = parseInt(photonumber);
src = newSrc;
leafleft();
}
});
});
//BUTTONS
$('.custom_previous').bind('click', function(e) {
changeimageLeft();
});
$('.custom_next').bind('click', function(e) {
changeimageRight();
});
//LEAFLET
map = L.map('image-map').setView([0, 0], 2);
layer = L.tileLayer.zoomify(oldSrc, {
width : 8688,
height : 5792,
minZoom : 1,
maxZoom : 4,
attribution : 'LBNV',
unloadInvisibleTiles : true
}).addTo(map);
var southWest = map.getBounds().getSouthWest(),
northEast = map.getBounds().getNorthEast(),
bounds = L.latLngBounds(southWest, northEast);
map.setMaxBounds(bounds);
}
//URL CHANGE
function leafleft() {
layer.setUrl(newSrc);
oldSrc = newSrc;
}
//LEFT BUTTON
function changeimageLeft() {
if (imgcounter == 80) {
imgcounter = 1;
newSrc = path + "00" + imgcounter + extension;
} else if (imgcounter >= 1 && imgcounter < 10) {
imgcounter++;
if (imgcounter == 10) {
newSrc = path + "0" + imgcounter + extension;
} else {
newSrc = path + "00" + imgcounter + extension;
}
} else {
imgcounter++;
newSrc = path + "0" + imgcounter + extension;
}
common();
}
//RIGHT BUTTON
function changeimageRight() {
if (imgcounter == 1) {
imgcounter = 80;
newSrc = path + "0" + imgcounter + extension;
} else if (imgcounter >= 1 && imgcounter <= 10) {
imgcounter--;
if (imgcounter == 0) {
imgcounter = 1;
newSrc = path + "00" + imgcounter + extension;
} else if (imgcounter == 9) {
newSrc = path + "00" + imgcounter + extension;
} else {
newSrc = path + "00" + imgcounter + extension;
}
} else {
imgcounter--;
newSrc = path + "0" + imgcounter + extension;
}
common();
}
function common() {
layer.setUrl(newSrc);
oldSrc = newSrc;
$("#slider").slider('value', imgcounter);
}
</script>
</body>
</html>
The white screen transient that you see when changing the URL template of your Zoomify Tile Layer is very probably due to how Tile Layers (including the one from Zoomify plugin) behave when changing their URL: they redraw all their tiles using the new URL template, so there is a short duration when there is no image present.
You could mitigate this behaviour by simply using several Tile Layers and swapping them, instead of re-using the same one and changing its URL template. Then you would have like a Layers Control, but with your "Left" and "Right" buttons instead of one radio per layer.
However, you might still have a transient when the previous layer is swapped by the new one, so you might include a delay before actually removing the previous layer from the map.

User selectable CSS color schemes with cookie support

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

Change font size on my website with Javascript

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.

Javascript page reload while maintaining current window position

How do I refresh the page using Javascript without the page returning to
the top.
My page refreshes using a timer but the problem is it goes back to the top every time it reloads. It should be able to retain the current position of the page as it reloads.
P.S.
Additional mouse events are welcome if necessary to be a part of your suggestion.
I'm actually thinking of #idname to target on refresh but my HTML elements don't have IDs, only classes.
If you use JavaScript, this code will do the trick.
var cookieName = "page_scroll";
var expdays = 365;
// An adaptation of Dorcht's cookie functions.
function setCookie(name, value, expires, path, domain, secure) {
if (!expires) expires = new Date();
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function getCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function deleteCookie(name, path, domain) {
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-00 00:00:01 GMT";
}
function saveScroll() {
var expdate = new Date();
expdate.setTime(expdate.getTime() + (expdays*24*60*60*1000)); // expiry date
var x = document.pageXOffset || document.body.scrollLeft;
var y = document.pageYOffset || document.body.scrollTop;
var data = x + "_" + y;
setCookie(cookieName, data, expdate);
}
function loadScroll() {
var inf = getCookie(cookieName);
if (!inf) { return; }
var ar = inf.split("_");
if (ar.length == 2) {
window.scrollTo(parseInt(ar[0]), parseInt(ar[1]));
}
}
This works by using a cookie to remember the scroll position.
Now just add
onload="loadScroll()" onunload="saveScroll()"
to your body tag and all will be well.
Source(s): http://www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/cookies/scrollpos.htm
If there is a certain set of specific sections of the page that are possible initial "scroll to" points, then you can assign those sections CSS ids and refresh the page with an appended ID hash at the end. For example, window.location = http://example.com#section2 will reload the page and automatically scroll it down to the element with the id "section2".
If it's not that specific, you can grab the current scroll position prior to refresh using jQuery's .scrollTop() method on the window: $(window).scrollTop(). You can then append this to the refresh URL, and include JS on the page that checks for this in order to automatically scroll to the correct position upon page load:
Grab current scroll position
var currentScroll = $(window).scrollTop();
window.location = 'http://example.com#' + currentScroll;
JS that must run when DOM is ready in order to check for a currentScroll hash
$(function(){
if(window.location.hash !== ''){
var scrollPos = parseInt(window.location.hash.substring(1),10);
$(window).scrollTo(scrollPos);
}
});
If you don't like the idea of modifying the URL in the address bar (because you really want to hide what you're doing from the user for some reason), you could store the scrollTo() value in a cookie instead of the URL.
You can do it using a cookie based method:
<html>
<head>
<script type="text/javascript">
var refreshPeriod = 120; // 120 Seconds
function refresh()
{
document.cookie = 'scrollTop=' + filterScrollTop();
document.cookie = 'scrollLeft=' + filterScrollLeft();
document.location.reload(true);
}
function getCookie(name)
{
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if(((!start) && (name != document.cookie.substring(0, name.length))) || start == -1)
return null;
var end = document.cookie.indexOf(";", len);
if(end == -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deleteCookie(name)
{
document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function setupRefresh()
{
var scrollTop = getCookie("scrollTop");
var scrollLeft = getCookie("scrollLeft");
if (!isNaN(scrollTop))
{
document.body.scrollTop = scrollTop;
document.documentElement.scrollTop = scrollTop;
}
if (!isNaN(scrollLeft))
{
document.body.scrollLeft = scrollLeft;
document.documentElement.scrollLeft = scrollLeft;
}
deleteCookie("scrollTop");
deleteCookie("scrollLeft");
setTimeout("refresh()", refreshPeriod * 1000);
}
function filterResults(win, docEl, body)
{
var result = win ? win : 0;
if (docEl && (!result || (result > docEl)))
result = docEl;
return body && (!result || (result > body)) ? body : result;
}
// Setting the cookie for vertical position
function filterScrollTop()
{
var win = window.pageYOffset ? window.pageYOffset : 0;
var docEl = document.documentElement ? document.documentElement.scrollTop : 0;
var body = document.body ? document.body.scrollTop : 0;
return filterResults(win, docEl, body);
}
// Setting the cookie for horizontal position
function filterScrollLeft()
{
var win = window.pageXOffset ? window.pageXOffset : 0;
var docEl = document.documentElement ? document.documentElement.scrollLeft : 0;
var body = document.body ? document.body.scrollLeft : 0;
return filterResults(win, docEl, body);
}
</script>
</head>
<body onload="setupRefresh()">
<!-- content here -->
</body>
</html>
or you can do it with a form method:
<html>
<head>
<script type="text/javascript">
// Saves scroll position
function scroll(value)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = value.scrollTop;
}
// Moves scroll position to saved value
function scrollMove(el)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(el).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="scrollMove('divScroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br />
<div id="divScroll" onscroll="scroll(this);"
style="overflow:auto;height:100px;width:100px;">
<!-- content here -->
</div>
</form>
</body>
</html>
Just depends on your application's requirements and restrictions.
I would recommend refreshing only the part of the page you are interested in changing, using ajax. I mean, just replacing the content using javascript depending on the response of the ajax call. I would say you take a look at jQuery's ajax or get methods.
If you can give more information about what you are trying to do maybe I can be of more assistance. Anyway, I hope this helps a little bit.
Cheers!

Categories