Skip to content

Instantly share code, notes, and snippets.

@achingono
Created November 26, 2013 16:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save achingono/7661804 to your computer and use it in GitHub Desktop.
Save achingono/7661804 to your computer and use it in GitHub Desktop.
Dynamically Enable/Disable CSS files
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title></title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="/Content/Design.css">
<link rel="stylesheet" href="/Content/Print.css" disabled="disabled">
<link rel="stylesheet" href="/Content/Large.css" disabled="disabled">
</head>
<body>
<h1>How to enable/disable CSS file references using javascript</h1>
<a href="#" data-toggle-css="Print.css">Click here</a> to toggle the "Print.css" file.
<a href="#" data-toggle-css="Large.css">Click here</a> to toggle the "Large.css" file.
<script src="/Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// get all the css stylesheets
//var styleSheets = document.styleSheets;
var styleSheets = document.getElementsByTagName("link");
// enable/disable a CSS file by suffix
function enableCSS(suffix, enabled)
{
for(var i = 0; i < styleSheets.length; i++) {
var styleSheet = styleSheets[i];
var href = styleSheet.href;
// check if the href "ends with" the suffix
if (href && href.indexOf(suffix, href.length - suffix.length) !== -1) {
styleSheet.disabled = !enabled;
break;
}
}
}
// disable all optional CSS files
$('[data-toggle-css]').each(function() {
// get a reference to the object
var self = $(this);
var suffix = self.data('toggle-css');
// disable the CSS
enableCSS(suffix, false);
});
// toggle the CSS files when trigger is clicked
$(document).on('click', '[data-toggle-css]', function(e) {
e.preventDefault();
var self = $(this);
var suffix = self.data('toggle-css');
var enabled = self.data('toggle-value') || false;
// enable/disable the CSS
enableCSS(suffix, enabled);
// change the toggle value
self.data('toggle-value', !enabled);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment