Minimize Sidebar Component
need
Use js to design a component that minimizes the sidebar.
- A sidebar is displayed on the right side of the page, and there is a "close" button at the bottom of the sidebar
- Click the "Collapse" button to hide the sidebar and reveal a small expand button
- Click the expand button to redisplay the sidebar
code
Here is the JavaScript code for a simple component that minimizes the sidebar:
<!DOCTYPE html>
<html>
<head>
<title>Minimize Sidebar Component</title>
<style>
#sidebar {
position: fixed;
top: 0;
right: 0;
width: 200px;
height: 100%;
background-color: #f0f0f0;
padding: 20px;
transition: transform 0.3s ease-in-out;
transform: translateX(0);
}
#sidebar.minimized {
transform: translateX(100%);
}
#toggle-sidebar {
position: fixed;
top: 50%;
right: 0;
transform: translateY(-50%);
background-color: #ccc;
border: none;
padding: 10px;
border-radius: 50%;
cursor: pointer;
display: none;
}
#toggle-sidebar.show {
display: block;
}
</style>
</head>
<body>
<div id="sidebar">
<h2>Sidebar Title</h2>
<p>Here is the sidebar content</p>
<button id="collapse-sidebar">Collapse</button>
</div>
<button id="toggle-sidebar">Expand</button>
<script>
const collapseButton = document.getElementById('collapse-sidebar');
const toggleButton = document.getElementById('toggle-sidebar');
const sidebar = document.getElementById('sidebar');
// Add a click event handler for the "Collapse" button
collapseButton.addEventListener('click', () => {
sidebar.classList.add('minimized');
toggleButton.classList.add('show');
});
// Add a click event handler for the expand button
toggleButton.addEventListener('click', () => {
sidebar.classList.remove('minimized');
toggleButton.classList.remove('show');
});
</script>
</body>
</html>
In this example, we use the transform
property in CSS to control the display state of the sidebar, use translateX
to translate the sidebar from the right side of the page, and use translateX(100%)
to translate it Go back to achieve the hidden effect. Also, use the transition
property to animate this transition.
In the JavaScript code, we add click event handlers for the #collapse-sidebar
and #toggle-sidebar
elements to control the minimization and expansion of the sidebar, respectively.
Comments