How to change an additional stylesheet using jQuery?

I have base.css and red.css on my site.

I like when changing red.css for blue.css, when I press some button without losing base.css, how to do it? I tried this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
    if($.cookie("css")) {
     $("link").attr("href",$.cookie("css"));
  }
$(document).ready(function(){  
    $("#troca_faccao").click(function() {
        $(this).parent().find("#painel_faccao").slideDown('fast').show(); //Drop down the subnav on click  
        $(this).hover(function() {
        }, function(){  
            $(this).parent().find("#painel_faccao").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
            });
        })
    $("#painel_faccao li a").click(function() { 
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
     return false;
  });
});
</script>

and div:

                        <div id="painel_faccao" style="display: none">
                        <p>A Escolha é Sua!</p>
                        <ul>
                            <li class="horda"><a href="#" rel="horde.css">HORDA</a></li> 
                            <li class="alianca"><a href="#" rel="aliance.css">ALIANÇA</a></li> 
                        </ul></div>
+5
source share
2 answers

You can use the filter selector :eqor eq()to target the stylesheet you want:

$("link:eq(0)").attr("href",$(this).attr('rel'));

Specify the position eqfor the stylesheet that you want to change href. You want to change the hreflink stylesheet pointing to red.css, rather thanbase.css


id , href ofL

<link id="someID"............/>

:

$("link#someID").attr("href",$(this).attr('rel'));
+3

http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/

tl; dr:

- HTML:

<link id="styles" rel="stylesheet" type="text/css" href="red.css" /> in HTML

- jQuery:

$("#styles").attr("href","blue.css");
+2

All Articles