Casper Round
Casper Round

Reputation: 343

Javascript option change head style.css

I have a relatively simple form with an option to select the theme. What I need is javascript to view the current selected option and change the style.css file depending on its class. For example, if Dark where selected in the option it would need to reokace style.css with dark.css Here is my select code:

<option value="<?= $_SESSION['user']['theme']?>">Current</option>
<option value="volvo">Dark</option>
<option value="saab">Light</option>
<option value="mercedes">Grass</option>
<option value="audi">Audi</option>
</select>

Upvotes: 0

Views: 78

Answers (2)

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

Try this example:

1) set css file path in option value

DEMO: http://jsfiddle.net/ptraxc90/8/

<link id="stylesheet" rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/le-frog/jquery-ui.css">
<select id="themes">
  <option value="http://code.jquery.com/ui/1.10.4/themes/le-frog/jquery-ui.css">Le Frog</option>
  <option value="http://code.jquery.com/ui/1.10.4/themes/start/jquery-ui.css">Start</option>
  <option value="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">Smoothness</option>
  <option value="http://code.jquery.com/ui/1.10.4/themes/redmond/jquery-ui.css">Redmond</option>
  <option value="http://code.jquery.com/ui/1.10.4/themes/sunny/jquery-ui.css">Sunny</option>
</select> 
<input type="submit" value="A submit button">

2) as select option changes get that value and change link css file path

$('#themes').change(function(){
    $("#stylesheet").attr({href : $('#themes').val()});
});

Upvotes: 4

TeT Psy
TeT Psy

Reputation: 341

I wouldn't recommend changing the actual style files, your just adding another request to the page, its way more efficient to add the different styles in one file, then add a class for the different styles with javascript.

css

option {
    background:white
}
.dark option {
    background:black
}

jQuery when option is selected

$('form').addClass('dark');

or

$('form').toggleClass('dark');

Upvotes: 0

Related Questions