Another Option:
Dynamically loading CSS files externally
I'm attempting to develop a dynamic webpage that changes its color using external .css files. I have written the code below, but upon clicking the href
, I do not see any changes. Can someone please point out what's wrong with my code? Any suggestions or ideas are appreciated.
<script language="JavaScript">
function loadjscssfile(filename, filetype)
{
if (filetype=="css")
{
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("mystyle.css", "css")
</script>
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a>
I have made some modifications to the code as shown below, yet I am still unable to get the desired output. No changes reflect on the page. Can anyone assist me in resolving this issue?
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="css/newstyle.css" />
<script language="JavaScript" type="text/javascript">
function loadjscssfile(filename, filetype)
{
if (filetype=="css")
{
var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.href = "filename";
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadjscssfile("oldstyle.css", "css")
</script>
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a>
</head>