Thursday, August 20, 2015

Changing CSS stylesheets dynamically

How do you change a style sheet dynamically? Below is an example code that changes the css style sheet when you click on a text.


HTML Code

<!doctyle html>
<html>
  <link rel='stylesheet' type='text/css' href='styleGreen.css'>
<body>
  <h1>Magic #1</h1>
  <a href='#' onClick='changeBkgColor();'>Click to change background color</a>
</body>
</html>
<script>
function changeBkgColor() {
   var linkTags = document.getElementsByTagName('link');
   for(var i=0; i< linkTags.length; i++) {
      linkTags[i].temp =  ('styleBlue' == linkTags[i].temp) 
                                  ? 'styleGreen' : 'styleBlue';
      linkTags[i].href = linkTags[i].temp + '.css';
   }
}
</script>


CSS File - styleGreen.css

body {
   background-color: green;
}
a:link{
 color: #00FFFF;
}
a:visited{
 color: white;
}
a:hover{
 color: yellow;
}


CSS File 2 - styleBlue.css

body {
   background-color: blue;
}
a:link{
 color: #CCCCFF;
}
a:visited{
 color: white;
}
a:hover{
 color: yellow;
}

No comments:

Post a Comment