Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you change the attached CSS file with Javascript?

I was wondering, is it possible to change the attached stylesheet using JavaScript?

For example:

<link href="stylesheet.css" rel="stylesheet" type="text/css">
.....
<div id="controls">
    <div id="red" onClick="styler(1)">R</div>
    <div id="green" onClick="styler(2)">G</div>
    <div id="blue" onClick="styler(3)">B</div>
    <div id="reset" onClick="styler(4)">Reset</div>
</div>

JavaScript

function styler(attr){
    switch(attr){
         case'1':document.----- = "stylesheet1.css";break;
         case'2':document.----- = "stylesheet2.css";break;
         case'3':document.----- = "stylesheet3.css";break;
         case'4':document.----- = "stylesheet.css";break;
         default:;break;
     }
}
like image 579
MCMXCII Avatar asked Mar 19 '23 09:03

MCMXCII


1 Answers

Add an id to the link tag and use

<link id="myStyleSheet" href="stylesheet.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    function styler(attr){
        var href;
        switch(attr){
            case'1':href = "stylesheet1.css";break;
            case'2':href = "stylesheet2.css";break;
            case'3':href = "stylesheet3.css";break;
            case'4':href = "stylesheet.css";break;
            default:;break;
        }
        document.getElementById('myStyleSheet').href = href;
    }
</script>

See this post

like image 114
Preston S Avatar answered Apr 02 '23 04:04

Preston S