Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function doesn't respond to ".click" until I move the cursor?

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

like image 547
Charles Watson Avatar asked Aug 14 '15 15:08

Charles Watson


1 Answers

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')
like image 185
m0meni Avatar answered Oct 25 '22 20:10

m0meni