Skip to content

Instantly share code, notes, and snippets.

@matijs
Last active December 8, 2016 22:47
Show Gist options
  • Save matijs/94e39a9e5821d9d6dbdecaf6ebadd322 to your computer and use it in GitHub Desktop.
Save matijs/94e39a9e5821d9d6dbdecaf6ebadd322 to your computer and use it in GitHub Desktop.
Stylesheet switcher sans ES6 features
(function() {
window.addEventListener( 'load', function() {
var links = Array.prototype.slice.call( document.querySelectorAll( 'link[title]') );
var uniqueTitles = links.reduce( function( titles, link ) {
if ( titles.indexOf( link.title ) === -1 ) {
titles.push( link.title );
}
return titles;
}, []);
var title = window.sessionStorage && window.sessionStorage.getItem( 'title' ) || '';
var select;
var option;
var i = 0;
function selectStyle( title ) {
links.forEach( function( link ) {
link.disabled = true;
link.disabled = link.title !== title;
});
if ( window.sessionStorage ) {
window.sessionStorage.setItem( 'title', title );
}
}
if ( uniqueTitles.length > 1 ) {
if ( title ) {
selectStyle( title );
}
select = document.createElement( 'select' );
select.setAttribute( 'style', 'position: absolute; top: 1em; right: 1em;' );
for ( ; i < uniqueTitles.length; i++ ) {
option = document.createElement( 'option' );
option.text = 'CSS: ' + uniqueTitles[ i ];
option.value = uniqueTitles[ i ];
option.selected = uniqueTitles[ i ] === title;
select.add( option );
}
document.body.appendChild( select );
select.addEventListener( 'change', function( event ) {
title = event.target.options[ event.target.selectedIndex ].value;
selectStyle( title );
});
}
});
}());
@matijs
Copy link
Author

matijs commented Dec 8, 2016

sessionStorage is probably good enough

@matijs
Copy link
Author

matijs commented Dec 8, 2016

Wait for the document to have fully loaded so that all stylesheets are available

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