How to switch style sheets using jQuery?

I developed a multi-color template, and now I only want to change the “CSS” file when I click on the color icon, can anyone help me?

This is my code, but it does not work well, just change the color only once.

$(document).ready(function() { $("a.silver").click(function() { $("a.silver").append('<link rel="stylesheet" type="text/css" href="themes/silver/css/template.css"/>'); }); $("a.red").click(function() { $("a.red").append('<link rel="stylesheet" type="text/css" href="css/template.css"/>'); }); }); 
+4
source share
3 answers

So, as some of the comments say, your best bet is to switch CSS classes. But if you change the style of the whole page, then sharing style sheets seems like a great idea to me. But you don’t need to “restore” elements every time you want to change style sheets. you probably better just separate them from the DOM as needed. So something like this:

 $(document).ready(function() { var sheets = { //a map of sheets. Simply add sheets to this to add more themes (and create appropriate links to them) silver: $('<link rel="stylesheet" type="text/css" href="themes/silver/css/template.css"/>'), red: $('<link rel="stylesheet" type="text/css" href="css/template.css"/>') }; var currentSheet = sheets.red.appendTo($("head")); //attach default sheet $("a.swapStyle").click(function () { currentSheet.detach(); //remove the current sheet currentSheet = (sheets[$(this).attr("data-theme")]).appendTo($("head")); //attach a new sheet and set the currentSheet variable to remember it. }); }); 

You will need to change your links to something like this:

 <a href="javascript:void(0)" class="swapStyle" data-theme="red">Change to red theme</a> <a href="javascript:void(0)" class="swapStyle" data-theme="silver">Change to silver theme</a> 
+3
source

Link to Css should be added to the head

  $(document).ready(function() { //load silver automatically in ready $("a.silver").click(function() { $('head > link').last().remove(); //removes red and adds silver $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />'); }); $("a.red").click(function() { $('head > link').last().remove(); //remove silver - adds red .append('<link rel="stylesheet" type="text/css" href="themes/silver/css/template.css"/>'); }); }); }); 

the actual stylesheets in my jQuery are incorrect

+1
source

As mentioned earlier, it is probably best to switch css styles rather than files, but if file switching is required, try:

 $(function(){ $('a.silver').click(function (){ $('link[href="css/template.css"]').attr('href','themes/silver/css/template.css'); }); $('a.red').click(function (){ $('link[href="themes/silver/css/template.css"]').attr('href','css/template.css'); }); }); 

In this decision, you must also define the style in your head, as usual ...

+1
source

Source: https://habr.com/ru/post/1432750/


All Articles