<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" id="maincss" href="style.css"/>
</head>
<body>
<h1>Header Text</h1>
<div class="clickme">
<!-- using onclick is generally bad practice. Only doing it here for brevity. -->
<button onclick="toggleCss()">Toggle</button>
</div>
<script src="load-css.js"></script>
</body>
</html>
// Code goes here
button{
position: fixed; bottom: 0; left: 0; right: 0;
}
# Using Javascript to set\reset stylesheets at runtime.
h1, h2, h3, h4, h5, h6 {
color: red !important;
}
h1, h2, h3, h4, h5, h6 {
color: green !important;
}
//-- we're *intentionally* not using jquery here, but I'm aliasing the document as $ for convenience.
var $ = document;
var user_cssnodeid = 'usercss';
var sheets = [
'main.css', 'other-main.css'
];
var current_usercss = '';
var new_usercss = '';
function toggleCss() {
//-- ternary: basically a condensed if\else. If current is sheets[0], set new to sheets[1]. If it's not, set new to sheets[0]
new_usercss = current_usercss === sheets[0] ? sheets[1] : sheets[0];
if (!$.getElementById(user_cssnodeid)) {
//-- the link element isn't there, so we'll need to create it first.
addNewCss();
}
else {
//-- the element is already there, so we just need to set it's src.
resetCss();
}
//-- we're done resetting css sheets. assign current to new.
// you *could* reuse the new_usercss string here, but - for stability's sake - we're reading the href from what's *actually* there now.
current_usercss = $.getElementById(user_cssnodeid).getAttribute('href');
}
/**
* Creates a new link element, sets its params according to what we want, add appends it to the document head
*/
function addNewCss() {
var head = $.getElementsByTagName('head')[0];
//-- using the dom api to create a new link element
var link = $.createElement('link');
link.id = user_cssnodeid;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = new_usercss;
link.media = 'all';
head.appendChild(link);
}
/**
* since the element with our target id is there, we don't need to create it. Simply select it and set its href attribute.
*/
function resetCss() {
var link = $.getElementById(user_cssnodeid);
link.href = new_usercss;
link.media = 'all';
}