Skip to content

Instantly share code, notes, and snippets.

@pixeline
Last active May 26, 2019 03:44
Show Gist options
  • Save pixeline/8248531 to your computer and use it in GitHub Desktop.
Save pixeline/8248531 to your computer and use it in GitHub Desktop.
Simple way to implement a stylesheet switcher, using jquery and proper html. Add your stylesheets to your <head> tag: <link rel="alternate stylesheet" title="red" href="css/red.css" type="text/css"> Include the jquery stylesheet switcher. Done.
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<link rel="stylesheet" title="main" href="normalize.min.css" type="text/css">
<link rel="stylesheet" title="main" href="main.css" type="text/css">
<link rel="alternate stylesheet" title="red" href="red.css" type="text/css">
<link rel="alternate stylesheet" title="blue" href="blue.css" type="text/css">
</head>
<body>
<p>Hello World</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.1.min.js"><\/script>')</script>
<script src="stylesheet-switcher.js"></script>
</body>
</html>
// STYLESHEET SWITCHER
(function($)
{
// All Alternate stylesheets Selector
var $links = $('link[rel*=alternate][title]');
$('body').prepend('<div id="toolbar"><select id="css-selector"></select></div>');
var options= '<option value="">Select stylesheet:</option>';
$links.each(function(index,value){
options +='<option value="'+$(this).attr('href')+'">'+$(this).attr('title')+'</option>';
});
$links.remove();
$('#css-selector').append(options)
.bind('change',function(){
$('link[rel*=jquery]').remove();
$('head').append('<link rel="stylesheet jquery" href="'+$(this).val()+'" type="text/css" />');
});
}
)(jQuery);
@soulbone
Copy link

Just a suggestion I haven't actually tested the code but am just wondering there's no option to switch the style sheet.. For instance input type ="button" value ="theme" onclick=" switchFunction();"
where the switchFucntion(); would enable you to switch the alternative css. From glancing through I notice only hello world on the page. nothing else. May be am mistaken somewhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment