Look at the code below...
First in HTML
In the markup, we have a sidebar open button class="opened"
, a sidebar close button button class="closed"
and the sidebar itself div class="sidebar"
inside the aside
semantic tag. Note that the close button for the panel is inside the panel itself. Those. it appears on the user's screen only when the panel is open, which is logical.
Now take a look at the CSS
The visual styles of the buttons are not particularly interesting. Interesting sidebar styles. It is positioned fixedly relative to the browser window. In order for the panel to occupy the entire height of the screen, the top: 0
and bottom: 0
properties are set. In addition, by default, we hide the panel outside the visible area using our transform: translateX(-100%)
property. The percentage sizes for this property are calculated based on the size of the block to which it is applied. Those. -100% shifts the panel to the left by its full width.
Notice the .sidebar.active
selector. It will take effect when the sidebar has both the .sidebar
class and the .active
class. In this selector, we remove the shift of the sidebar outside the visible area. This means that the sidebar with the .active
class is visible to the user.
Now let's take a look at JS
First, we define the identifiers of the elements we need - the open, close and sidebar buttons. This will be needed for what follows. Obviously, when the open button is clicked, we need to add the active class to the sidebar. We defined the function of adding this class for the click event in the addEventListener
method.
On the close button we hang a click listener and a deletion function of the .active
class for the sidebar.
Here's a simple technique.
const open = document.querySelector('.opened');
const close = document.querySelector('.closed');
const sidebar = document.querySelector('.sidebar');
open.addEventListener('click', () => {
sidebar.classList.add('active');
});
close.addEventListener('click', () => {
sidebar.classList.remove('active');
});
body {
margin: 0;
}
.opened,
.closed {
border: none;
padding: 0;
width: 48px;
height: 48px;
display: flex;
justify-content: center;
align-items: center;
}
.sidebar {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: 250px;
background-color: #e9e9ed;
transform: translateX(-100%);
transition: .2s;
}
.closed {
position: absolute;
top: 0;
right: 0;
}
.sidebar.active {
transform: translateX(0);
}
<button class="opened"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M24 6h-24v-4h24v4zm0 4h-24v4h24v-4zm0 8h-24v4h24v-4z"/></svg></button>
<aside>
<div class="sidebar">
<button class="closed"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M23 20.168l-8.185-8.187 8.185-8.174-2.832-2.807-8.182 8.179-8.176-8.179-2.81 2.81 8.186 8.196-8.186 8.184 2.81 2.81 8.203-8.192 8.18 8.192z"/></svg></button>
</div>
</aside>