Last active
December 8, 2016 22:47
-
-
Save matijs/94e39a9e5821d9d6dbdecaf6ebadd322 to your computer and use it in GitHub Desktop.
Stylesheet switcher sans ES6 features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 ); | |
}); | |
} | |
}); | |
}()); |
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
sessionStorage is probably good enough