irm
irm

Reputation: 4331

Jquery if statement to check current stylesheet

I'm working on a web app and switching stylesheets to let user select different themes.

I have the fallowing code:

$('#theme_selector_white').click(function (){
   $('link[href="default_teal.css"]').attr('href','white_style.css');
});
$('#theme_selector_teal').click(function (){
   $('link[href="white_style.css"]').attr('href','default_teal.css');
});  
$('#theme_selector_sopia').click(function (){
   $('link[href="    "]').attr('href','sopia_style.css');
});

My code works if alternating 2 different stylesheets but once I add a third one I need to check what the current one is so I can replaced current stylesheet with the intended one.

I believe I need to do something like this for every selector:

$('#theme_selector_white').click(function(){
     if ( current stylesheet == "default_teal.css") {
           //replace default_teal.css with intended stylesheet
     }
     else {
          //replace sopia_style.css with intended stylesheet

     }

I need help writing the condition to check for current stylesheet.

I will really appreciate any help..

Upvotes: 1

Views: 108

Answers (2)

Barmar
Barmar

Reputation: 782508

Here's a DRY solution. First, as Travis said, give the link an ID:

<link id="userSelectedCss" rel="stylesheet" ...>

Then change your selector elements to:

<a class="theme_selector" href="#" data-css="white_style.css">White</a>
<a class="theme_selector" href="#" data-css="sopia_style.css">Sopia</a>
<a class="theme_selector" href="#" data-css="default_style.css">Default</a>

and change your jQuery to:

$(".theme_selector").click(function(e) {
    e.preventDefault(); // Override the normal link click action.
    $("#userSelectedCss").attr("href", $(this).data("css"));
});

Upvotes: 2

Travis J
Travis J

Reputation: 82337

Give an id to your link element

<link id="userSelectedCss" ...>

and then target it

$('#theme_selector_white').click(function (){
 $('#userSelectedCss').attr('href','white_style.css');
});
$('#theme_selector_teal').click(function (){
 $('#userSelectedCss').attr('href','default_teal.css');
});  
$('#theme_selector_sopia').click(function (){
 $('#userSelectedCss').attr('href','sopia_style.css');
});

Upvotes: 3

Related Questions