Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load in an external CSS file dynamically?

I'm trying to create a dynamic page using external .css pages where the page color will get changed. Below is my code. But when I click the href, I am not getting any output. Can anyone please tell me what's the problem in my code?

<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 modified my code as below. Still, I'm facing the problem of getting the output. No result. Can anyone please help me out?

<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>
like image 250
Patel Avatar asked Jan 20 '10 06:01

Patel


1 Answers

Try this:

var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.href = "filename";
document.getElementsByTagName("head")[0].appendChild(fileref)
like image 182
Tim Goodman Avatar answered Sep 19 '22 09:09

Tim Goodman