Search code examples
jquerycssbuttonstylesheet

Toggle between stylesheets with one button


I'd like to toggle between two stylesheets using a single button. The code I have currently is:

<link id="style1" rel="stylesheet" type="text/css" href="style.css" />
<link id="style2" rel="stylesheet" type="text/css" href="styleinvert.css" disabled="disabled" />

<script>
    function toggle() {
        var el1 = document.getElementById("style1"),
            el2 = document.getElementById("style2");
        if( el1.disabled == "disabled" ) {
            el1.disabled = undefined;
            el2.disabled = "disabled";
        } else {
            el1.disabled = "disabled";
            el2.disabled = undefined;
        }
    }
</script>

<a href="#" onclick="toggle()">Invert</a>

However this causes the stylesheet to temporarily disappear between deactivating the first one and activating the new one.

Is there a better way to do this? Ideally I'd just to add a small snippet of style for the second stylesheet seen as I only need to change a few things like font color etc.


Solution

  • Here's a basic example of what I mean by adding a class to the body and writing override styles...

    function toggle(){
        $('body').toggleClass('style2');
    }
    
    // css
    
    p{
        color:green;
    }
    
    .style2 p{
        color:red;
    }
    

    the jquery toggle class docs: http://api.jquery.com/toggleclass/