1

So, unlike other questions about this, I want to use this code from here: How do I switch my CSS stylesheet using jQuery?

I need to switch between multiple css styles instead of two with the following code (jQuery):

$('#backgroundDefault').click(function (){ $('link[href="style1.css"]').attr('href','style.css'); }); $('#background1').click(function (){ $('link[href="style.css"]').attr('href','style1.css'); });

Can this work? I like the smooth transition between styles, unlike many other code samples I tried.

Community
  • 1
  • 1
Akidus
  • 191
  • 11

1 Answers1

1

Yes, it will work. Whether <link> is either in the <head> or <body>.

Here's a basic sample,

var isToggled = false;
$(function() {
  $('#btnSwitchCss').on('click', function() {
    isToggled = !isToggled;

    if (isToggled) {
      $("link[href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css']").attr('href', '../');
    } else {
      $("link[href='../']").attr('href', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');
    }
  })

});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <h2 class="text-center"> Switch CSS Style </h2>
  <button id="btnSwitchCss">Switch</button>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
choz
  • 17,242
  • 4
  • 53
  • 73
  • Haven't used Javascript as much as Jquery, could I switch between 4 styles? – Akidus May 27 '16 at 04:34
  • @Akidus Yes, you can switch to multiple styles with no problem. But this is such a bad practice though I can't fully prove it. Why would you want to do this? – choz May 27 '16 at 04:45
  • What do you recommend? Unless, you have an idea for switching between wallpaper on the same web page. – Akidus May 27 '16 at 05:06
  • @Akidus Yeah, assign each background wallpaper as their own class in your css. And switch the class instead. – choz May 27 '16 at 05:25
  • You you have an example? For some reason, I can't think of the code right now. – Akidus May 27 '16 at 05:40
  • @Akidus Look at this [answer](http://stackoverflow.com/a/4917267/1627271). And there should be lot of samples out there.. – choz May 27 '16 at 05:43