I have a website with a simple CSS style switcher. I use the following code for the function that handles clicking the two theme buttons, initiating the switch from dark to light and vice versa:
<script>
$(function() {
$(".light").click(function(){
$("link").attr("href", "css/lightHome.css");
$(".light").attr("disabled", "disabled");
$(".dark").removeAttr("disabled", "disabled")
})
$(".dark").click(function(){
$("link").attr("href", "css/home.css");
$(".dark").attr("disabled", "disabled");
$(".light").removeAttr("disabled", "disabled")
})
});
</script>
Everything about it operates exactly as I want, except the fact that when I click the button, nothing happens. But the second I shift the cursor position after the click, then the switch occurs. I don't have the best jQuery grasp, so I am hoping it is a simple lack of understanding regarding the DOM processes. Possibly having to do with the lack of "on ready"?
I've tried clicking and waiting several minutes, and nothing happens until I move the cursor.
The website:
http://watsoncn.info
Instead of completely switching the CSS file, an alternative solution would be to have a single CSS file with both your styles and then prefixing all your selectors with .theme.dark
or .theme.light
;
This would be pretty easy to do with nesting in LESS or SASS if you're using them (if you're not, you really should consider it. I can't imagine writing CSS without a preprocessor now), but might be cumbersome in pure CSS.
CSS:
.theme.dark <rest of selectors> {
//CSS
}
.theme.light <rest of selectors> {
//CSS
}
HTML:
<body class="theme">
and then code that runs on button clicks would be
$('body').addClass('dark')
$('body').removeClass('light')
and
$('body').addClass('light')
$('body').removeClass('dark')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With