Javascript: Change CSS File Dynamically + Cookie
maybe this could help you..
(function() {
var e = document.createElement('link');
e.href = document.location.protocol + '//example.com/file.css';
e.type = 'text/css';
e.rel = 'stylesheet';
e.media = 'screen';
document.getElementsByTagName('head')[0].appendChild(e);
}());
Edit, full JavaScript without jQuery
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);
}
document.addEventListener('DOMContentLoaded',function(){
if(readCookie('css')){
var e = document.getElementById('test-css'); // <link href="..." id="test-css"/>
e.href = readCookie('css');
}
var element = document.getElementById('change-css'); // <a herf="#" id="change-css" rel="file.css">Click Here</a>
element.addEventListener('click', function (event) {
var e = document.getElementById('test-css');
e.href = this.rel;
if(readCookie('css')){
eraseCookie('css');
}
createCookie('css',this.rel,365);
event.preventDefault();
}, false);
})
Dynamically change css files
I believe you could achieve this through using html data attributes instead of using separate CSS files if it is a theme change you are going for.
function switchTheme(e) { let theme = document.getElementById("theme-selector").value; let app = document.getElementById("app"); app.setAttribute('data-theme', theme);}
[data-theme="1"] { --foreground-color: #eeeeee; --background-color: #222222;}
[data-theme="2"] { --foreground-color: #000000; --background-color: #eeeeee;}
h1 { color: var(--foreground-color); background-color: var(--background-color);}
<div id="app" data-theme="1"> <h1>A cool title with different colors...</h1></div>
<select id="theme-selector" onchange="switchTheme()"> <option value="1">Theme 1</option> <option value="2">Theme 2</option></select>
Dynamically Switching CSS Files
First, start by defining the original style like this:
HTML:
<link id="style" rel="stylesheet" type="text/css" href="style.css" />
Notice the id=style
that we'll use to find the element. That might fix your first error.
For the second one, you have to decide whether to use document.addEventListener( 'DOMContentLoaded', bindEvents, false );
or window.onload
because they're different functions. This might help you window.onload vs. body.onload vs. document.onready.
So, now we can do some Javascript:
HTML (the links):
<li><button onclick='setStyle("css/style.comicsans.css")'>JB's Fav Font</button></li>
<li><button onclick='setStyle("css/style.other.css")'>Other Font</button></li>
First, notice that I'm only using a parameter to call setStyle
function on click, and btw it's better to work with <button>
, this way we get a cleaner result.
Javascript:
var cssStyle = document.getElementById('style');
window.onload = function(){
if(localStorage && localStorage.getItem("style"))
cssStyle.href = localStorage.getItem("style");
};
function setStyle(newStyle){
cssStyle.href = newStyle;
if(localStorage)
localStorage.setItem("style", newStyle);
};
BONUS:
But if you are only be using two styles, then try to simplify, and do a shorthand method to do this:
HTML:
<li><button onclick='toggleStyle()'>Toggle</button></li>
<!-- cssswitcher js -->
<script type='text/javascript'>
var cssStyle = document.getElementById('style');
var listStyles = ["css/style.comicsans.css", "css/style.other.css"];
window.onload = function(){
if(localStorage && localStorage.getItem("style"))
cssStyle.href = localStorage.getItem("style");
};
function toggleStyle(){
var previousStyle = cssStyle.href;
if(previousStyle.endsWith(listStyles[0]))
newStyle = listStyles[1];
else
newStyle = listStyles[0];
cssStyle.href = newStyle;
if(localStorage)
localStorage.setItem("style", newStyle);
};
</script>
Replacing css file on the fly (and apply the new style to the page)
You can create a new link, and replace the old one with the new one. If you put it in a function, you can reuse it wherever it's needed.
The Javascript:
function changeCSS(cssFile, cssLinkIndex) {
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link");
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(cssLinkIndex).replaceChild(newlink, oldlink);
}
The HTML:
<html>
<head>
<title>Changing CSS</title>
<link rel="stylesheet" type="text/css" href="positive.css"/>
</head>
<body>
<a href="#" onclick="changeCSS('positive.css', 0);">STYLE 1</a>
<a href="#" onclick="changeCSS('negative.css', 0);">STYLE 2</a>
</body>
</html>
For simplicity, I used inline javascript. In production you would want to use unobtrusive event listeners.
Cookies - js file data is not updating dynamically
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.
How to use JavaScript to change a cascading style sheet dynamically
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 "";
}
JavaScript to change CSS dynamically when scrolling
The error was because I didn't add 'px' string when setting new CSS values.
So, the js code would be:
import './style.css'
function parallel_height_js(){
let scroll_top = window.scrollY;
let header_height = document.getElementsByClassName("sample-header-section")[0].clientHeight;
document.getElementsByClassName("text-section")[0].style.marginTop = header_height+'px';
document.getElementsByClassName("sample-header")[0].style.height = (header_height - scroll_top)+'px';
}
parallel_height_js();
window.onscroll = parallel_height_js;
window.onresize = parallel_height_js;
HTML:
<header>
<div class="sample-header">
<div class="...">
<input type="checkbox" id="menu" />
<label for="menu"></label>
<div class="menu-content">
<ul>
<li><a href="">Contact</a> </li>
<li><a href="">About Us</a> </li>
</ul>
</div>
</div>
<div class="sample-header-section">
<h1>...</h1>
<h2>...</h2>
</div>
</div>
</header>
How do i add a cookie to cache stylesheet change in this script
I think cookies are a bit overkill for this and are not really needed. You can do this a nice way with localStorage
instead if you don't have to use cookies for other various reasons not stated.
https://jsfiddle.net/4bqehjfc/3/
var fullWidth = function() {
$('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
},
fixedWidth = function() {
$('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();
};
$("#full-width").click(function () {
localStorage.setItem('width', 'full-width');
fullWidth();
});
$("#fixed-width").click(function () {
localStorage.setItem('width', 'fixed-width');
fixedWidth();
});
if (localStorage.getItem('width') == 'fixed-width') {
fixedWidth();
} else if (localStorage.getItem('width') == 'full-width') {
fullWidth();
}
The important bit is: localStorage.setItem()
and localStorage.getItem()
.
localStorage is well supported and offers a nice clean alternative to Cookies (for some purposes) but also has it's own limitations. See here.
One important thing to note is switching stylesheets like this you are going to flashes of unstyled content whilst the stylesheets are fetched which isn't very nice. You would want to use localstorage
to append a CSS class and change the styles this way if you have the flexibility to do so.
Related Topics
How to Disable Ie10 History Swipe Gesture
How to Position a React Component Relative to Its Parent
How to Change the Font Size in Jqgrid
Slow Response When the HTML Table Is Big
Getting Last-Child of a Div in IE8
Auto Image Resize Based on Browser Window Dimensions
How to Get a Dom Element's ::Before Content with JavaScript
Custom Cursor Interaction Point - CSS/Jquery
Can Bootstrap (4) Be Integrated Along with Angular Material (2)
Force Address Bar to Show in Mobile Chrome App
How to Open Bootstrap Modal in Ajax Success
Adding to Script Bundle from Partial View in .Net MVC 5
A Way to Count Columns in a Responsive Grid
Css/JavaScript Use Div to Grey Out Section of Page
Can't Figure Out Why Page Loads at Bottom? Angular Ui-Router Autoscroll Issue
Jquery .Show() Not Revealing a Div with Visibility of Hidden