1

Trying to do a dark-mode toggle on click of element

  1. toggle div class = .dark__mode
  2. css link class = .css-link
  3. css link href variable = style__old

I am learning jquery and i think there is a major problem with reasoning and structure of code

The link href changes at first but doesn't change back

Please help and or if using a checkbox option is better

window.onload = function(){

    var  style__old = $(".css-link").attr("href");

    $(".dark__mode").click(function(){

            if (style__old == "css/style.css"){
                var style__new = style__old.replace("style.css","dark-mode.css");
                $(".css-link").attr("href", style__new);
            }
            else
            if (style__old == "css/dark-mode.css"){
                style__old.replace("dark-mode.css","style.css");
                $(".css-link").attr("href", "style__old");
            }
    }

);}

1 Answer 1

1

The approach you're using of dynamically changing the loaded stylesheet is not very reliable.

A much better approach is to put all the relevant styles in to the page, in separate stylesheets, then toggle() a class on a low level element, such as the body, and hang all your selectors off that.

In practice it would look something like this:

jQuery($ => {
  $('.dark__mode').on('click', (e) => {
    e.preventDefault();
    $('body').toggleClass('dark');
  })
});
/* Normal layout */
div { color: #0C0; }
a { color: #C00; }

/* Dark layout */
body.dark {
  background-color: #333;
  color: #FFF;
}
body.dark div { color: #CCC; }
body.dark a { color: #CC0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="dark__mode">Toggle</a>
<div>
  <p>Lorem ipsum dolor sit</p>
  <a href="#">Amet consectetur adipcing elit</a>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.