I've been attempting to dynamically change the CSS file, but I've run into an issue:
Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function exits, the style reverts back to the default.
Below is the code I'm working with:
Javascript:
function checkStyle(evt) {
var selectedStyle = evt.options[evt.selectedIndex].value;
applyStyle(selectedStyle);
}
function applyStyle(index) {
var cssLinkIndex = 0;
var counter;
switch (index) {
case "1":
counter = "./StyleCss/style1.css";
break;
case "2":
counter = "./StyleCss/style2.css";
break;
case "3":
counter = "./StyleCss/style3.css";
break;
case "4":
counter = "./StyleCss/style4.css";
break;
default:
counter = "./StyleCss/style1.css";
}
changeCSS(counter, cssLinkIndex);
}
function changeCSS(cssFile, cssLinkIndex) {
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link");
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}
HTML
<script type="text/javascript" src="./JavaScript/script.js"></script>
<link rel="stylesheet" href="./StyleCss/style1.css">
<div class="Menu">
<select class="Style" onchange="checkStyle(this);">
<option value='1' selected='selected'>Style 1</option>
<option value='2'>Style 2</option>
<option value='3'>Style 3</option>
<option value='4'>Style 4</option>
</select>
</div>
Appreciate any assistance on this matter.