javascriptcsstoggle

Toggle sidebar div with another div using CSS/Javascript


here's my situation:

So I'm trying to toggle a sidebar by clicking another div. It's a 100% height sidebar that is fixed to the right side of the viewport. Essentially I am trying to wrap a 300px div around both the 50px wide toggle div and the 250px wide sidebar div, and I want to hide the sidebar portion using a negative margin-right pixel value. Using the .toggle:active selector (so this occurs when the toggle div is clicked), I want to show the sidebar portion by setting that margin-right pixel value back to 0px.

Code so far:

<div class="wrapper">
  <a href="#">
    <div class="toggle">Toggle</div>
  </a>
  <div class="cart">Cart</div>
</div>

CSS so far:

.wrapper {
  position:fixed;
  width:300px;
  height:100%;
  background-color:orange;
  top:0;
  right:0;
  margin-right:-250px;
}
.toggle {
  position:relative;
  display:block;
  width:50px;
  height:100%;
  background-color:grey;
  float:left;
}
.toggle:active .wrapper {
  margin-right:0px;
}
.cart {
  position: relative;
  width:250px;
  height:100%;
  background-color:red;
  float:right;
}

Here's the jsfiddle!

Here's my question:

How can I target .wrapper to change a css attribute when .toggle:active is engaged? Also, how can I specify when the sidebar is visible and when it's not?

I'm new to Javascript, but it seems like I'll need it to do this due to the callback function. If CSS-only is possible, I'd lean toward that solution. Please note that I want to use margin-right so that I can opt to use CSS transitions later to animate my element sliding left and right.


Solution

  • I would recommend using jQuery for this. It is simple and less chance for errors.

    $('.toggle').click(function() {
        $('.cart').toggle();
    });
    

    http://api.jquery.com/toggle/