0

I am working on my website and wanted to include a small toggle switch that changes the stylesheet to a dark version of the theme.

I've been having trouble finding out how I could archive this so that the toggle switch saves a cookie and if the cookie says "dark-mode" it will go to into the dark theme and if not, back to the light theme.

My current code is already able to enable the black theme, but I could not get it to save/use a cookie as I am not experienced enough with JavaScript to do that.

$('#mode').change(function(){   
    
    if ($(this).prop('checked'))
    {
        $('body').addClass('dark-mode');
    }
    else
    {
        $('body').removeClass('dark-mode');
    }
    
});
/* Light Theme Style */
h1 {
    color: #34495e;
  font-family: montserrat;
}
p {
    color: #2c3e50;
    font-family: montserrat;

}

/* Dark Theme Style */
body.dark-mode {
    background: #2c3e50;
}
.dark-mode h1 {
    color: #ecf0f1;
}
.dark-mode p {
    color: #bdc3c7;
}

/* Toggle Switch Style*/
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* Hide default HTML checkbox */
.switch input {display:none;}

/* The slider */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<style>
@import 'https://fonts.googleapis.com/css?family=Montserrat';
</style>


<label for="mode" class="switch">
  <input id="mode" type="checkbox">
  <div class="slider round"></div>
</label>

<h1>Hello!</h1>
<p>This is where my page content will be.</p>
Sainan
  • 1,228
  • 1
  • 20
  • 29
Ruxie
  • 69
  • 7
  • 1
    See http://stackoverflow.com/questions/1458724/how-do-i-set-unset-cookie-with-jquery for cookie usage with jquery ;-) – Tom B. Jul 27 '16 at 14:37
  • I'd suggest using [localstorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) to store this information. It's a lot easier to use than cookies and is widely supported enough by now. – Dave Jul 27 '16 at 14:45
  • Thanks for the answer, I figured out how I can set the cookie, but I'm not sure how I can get my javascript to set the dark mode depending on the cookie? Would it be possible that if the cookie exists that the checkbox is checked? – Ruxie Jul 27 '16 at 14:55

0 Answers0