Reputation: 205
I want to change the style of a page between two different .css files when the user clicks a link.
When the link is clicked, I want the new style to be loaded. When it is clicked a second time, I want the default style to be loaded. (In other words, I want to be able to toggle between two different stylesheets on a click event).
$(function(){
$('.default').click(function(){
$('#link').attr('href', 'defaultStyle' );
$('.default').addClass('new').removeClass('default');
});
});
$(function(){
$('.new').click(function(){
$('#link').attr('href', 'secondStyle' );
$('.new').addClass('default').removeClass('new');
});
});
The code above changed the style once, but the second block doesn't work.
How can I fix this? TIA.
Upvotes: 1
Views: 437
Reputation: 55
You can easily do it with jquery, here is an example,
$(document).ready(function(){
$('#blue').click(function(event) {
$('#text').css('background-color','blue');
});
$('#grey').click(function(event) {
$('#text').css('background-color','grey');
});
});
<div id="text" style="background-color:grey;" >Hello World</div>
<div id="blue" style="cursor:pointer" >blue</div>
<div id="grey" style="cursor:pointer" >grey</div>
Upvotes: 0
Reputation: 15583
The reason is that the jQuery selector is only finding elements with .new when the JavaScript is first executed.
You should look into jQuery.live() http://api.jquery.com/live/
Upvotes: 0
Reputation: 816384
The click handlers are assigned to the elements that currently exist. .new
does not exist yet when you execute the second block (only after you clicked .default
).
Just toggle the classes:
$(function(){
$('.default').click(function(){
$('#link').attr('href', function(i, v) {
return v === 'defaultStyle' ? 'secondStyle' : 'defaultStyle';
});
$(this).toggleClass('new').toggleClass('default');
});
});
Upvotes: 0
Reputation: 31642
Is this:
$('.new').addClass('default').removeClass('reader');
Supposed to be:
$('.new').addClass('default').removeClass('new');
Also, have you checked firefox / fiddler / etc to see if the browser is trying to download the second stylesheet?
Upvotes: 0