Skip to content

Instantly share code, notes, and snippets.

@matijs matijs/switcher-es5.js
Last active Dec 8, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Dec 8, 2016

sessionStorage is probably good enough

@matijs

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.