Search code examples
jquerycssstylesheet

Switching Stylesheets


I know this has been covered before - but I have my code in place in what seems to be a logical way, using jQuery, but the second 'click' function doesn't seem to be working.

It's quite probable I am missing something very simple, or doing something completely wrong...!

    <script type="text/javascript">    
        $(document).ready(function() {
          $('a[href=#start]').click(function(){
              $('html, body').animate({scrollLeft:0}, 'slow');
              return false;
          });

          $(".invert-link").click(function() {
           $("link[class='THEME']").attr("href", "http://link-to-site/wp-content/themes/HM/dark-style.css");
           $(".invert-link").addClass("dark");
            });

          $(".invert-link.dark").click(function() {
           $("link[class='THEME']").attr("href", "http://link-to-site/wp-content/themes/HM/light-style.css");
           $(".invert-link").removeClass("dark");
            });

        }); 
    </script>

The first section is unrelated, but could influence i guess!

Cheers guys!


Solution

  • Try this:

    $(".invert-link").click(function() {
    
        if ($(this).hasClass('dark')) {
            $("link[class='THEME']").attr("href", "http://link-to-site/wp-content/themes/HM/light-style.css");
            $(".invert-link").removeClass("dark");
        } else {
            $("link[class='THEME']").attr("href", "http://link-to-site/wp-content/themes/HM/dark-style.css");
            $(".invert-link").addClass("dark");
        }
    
    });
    

    Your first .invert-link selector will always fire because it always has that class, you could have used :not() to have two different actions depending on the class. Alternatively my code above shows that you can have just one click event, check if the dark class exists and work from there.

    Here's the example working.