1

So I'm having trouble toggling this switch to change the background color. Im not sure how to get it to remove the CSS that it applies to the document. I want it to toggle between to different colored backgrounds.

Here's my code:

<!Doctype html>
<html lang="en">
<head>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <label class="switch"><input id="input" type="checkbox" /><div></div></label>
    </div>
    <footer>
        <script src="https://code.jquery.com/jquery-2.2.1.js"></script>
        <script type="text/javascript" src="js.js"></script>
    </footer>
</body>
</html>

The Styles:

html {
background: #878476;
}

.container {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
height: 40px;
margin: auto;
text-align: center;
}

.switch input {
position: absolute;
opacity: 0;
}

.switch {
display: inline-block;
font-size: 20px; /* 1 */
height: 1em;
width: 2em;
background: #BDB9A6;
border-radius: 1em;
}

.switch div {
height: 1em;
width: 1em;
border-radius: 1em;
background: #FFF;
box-shadow: 0 0.1em 0.3em rgba(0,0,0,0.3);
transition: all 300ms;
transition: all 300ms;
transition: all 300ms;
}

.switch input:checked + div {
transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}

And the JS:

$(document).ready(function() {
console.log( "Coffee Isn't strong enough for me to remember how to toggle the OnClick" );
$(".switch").on("click", function() {
    $("html").css("background", "blue");
});
});
3
  • try addClass() and removeClass().. Commented Mar 14, 2016 at 4:25
  • Use .toggleClass() Commented Mar 14, 2016 at 4:25
  • 1
    jsfiddle.net/rayon_1990/eLgqe2ya/1 Commented Mar 14, 2016 at 4:55

1 Answer 1

1

You can use toggle class here is link for more information http://api.jquery.com/toggleclass/

$("#input").on("click", function() {
    $("html").toggleClass("bck-change");
});

And also i've modified your code pls refer: https://jsfiddle.net/eLgqe2ya/

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

2 Comments

Why "#input" instead of .switch ?
That's because generally checkbox is the proper element to attach events to, not the label, and the change event would normally be the proper event to use, not click.

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.