I get two error messages when trying to load the page with the code below. The error messages are:
- "Uncaught TypeError: Cannot set property 'href' of null at HTMLAnchorElement.col.(anonymous function).onclick (http://www.jimbrink.org/:363:17)"
- "Uncaught ReferenceError: bindEvents is not defined at (index):375"
I'm trying to create a link that, when clicked, would switch to another css file (with different fonts).
(BONUS QUESTION: Is there a way for the link to toggle between the two stylesheets?)
I've taken this from another StackOverflow question, but I can't seem to get the code to work my situation.
Here's the link:
<li><a href="#" class="changeStyle" data-style="css/style.comicsans.css" data-type="text/css" data-rel="stylesheet">JB's Fav Font</a></li>
Here's the js function from the bottom of the page:
<!-- cssswitcher js -->
<script type='text/javascript'>
window.onload = function bindEvents(){
var css=document.getElementById('style');
var col=document.querySelectorAll('a.changeStyle');
/* iterate through collection and assign listener */
for( var n in col )if( col[n].nodeType==1 ) col[n].onclick=function(e){
e.preventDefault();/* prevent jumping to top of page etc */
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
/* assign style attributes */
css.href=el.dataset.style;
css.rel=el.dataset.rel;
css.type=el.dataset.type;
/* store reference to style selected in localstorage */
localStorage.setItem( 'style', el.dataset.style );
};
/* if there is a reference to the user's css choice in storage, assign it */
if( localStorage.getItem( 'style' )!=null ) css.href=localStorage.getItem( 'style' );
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>