While I've found essentially the same question asked a number of times here and on other sites, I've spent hours and hours trying to get those answers to work on my site to no avail; I'm just plain stumped. Possibly because I'm fairly new to Javascript, self-taught, and I'm doing this in the first place to try to expand my skills, so I'm probably missing something blatantly obvious to anyone else.
In any event, on my website I have a div for a sidebar, and I'm using jQuery to toggle it and also adjust the parent div to compensate for its absence when it's hidden via a button. I'd like to be able to use a cookie so that I can refresh without it returning to its default state, but I've never used a cookie before and every tutorial I can find on the subject and every answer I can find to a similar question has resulted in code that just plain doesn't work for reasons I can't figure out.
Here's a JSFiddle of a simplified version of my website. (Though the toggle script isn't working there for some reason - it works on my website! I probably missed something when I was simplifying it, but I can't for the life of me figure out what.)
The HTML:
<div class="bgcontainer_center">
<div id="sidebar">
<p>Sidebar Content</p>
</div>
<div id="wrapper">
<div id="toggle">
<input type="button" value="Toggle Sidebar">
</div>
<p>Main Content</p>
</div>
</div>
The CSS:
.bgcontainer_center {
position: relative;
margin-left: auto;
margin-right: auto;
width: auto;
max-width: 500px;
background-color: #ff00ff;
height: 100%;
}
.bgcontainer_center.clicked {
max-width: 350px;
}
#sidebar {
float: left;
width: 25%;
max-width: 125px;
background-color: #00ff00;
height: 100%;
left: 0px;
}
#wrapper {
width: auto;
max-width: 350px;
background-color: #0000ff;
overflow-x: hidden;
}
And the jQuery:
$(document).ready(function () {
$("#toggle").click(function () {
$("#sidebar").toggle("slow");
$(".bgcontainer_center").toggleClass('clicked');
});
});
Help me? Bonus points if you can explain it to me so that I actually understand instead of just giving me code that works - I'm trying to learn here! And feel free to let me know if I've done anything else dumb with my coding.
Edit: Working version, tweaked to function as intended: https://jsfiddle.net/eo12xw79/3/
You can use
localStorage
to store the state.See the comments inline in the code:
Demo: https://jsfiddle.net/tusharj/eo12xw79/2/
LocalStorage
Doc: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage