Detecting the "swap" to close a menu with CSS
Think about your users when they visit your website on their mobile devices: allowing them to close your menu using a "swipe" will greatly enhance their experience on your site, providing a better user experience and increasing your chances of retaining them. Let’s discover together how to do this in this article!
Step 1
Let's start with the HTML code.
<div class="hamburger">
<span></span>
<span></span>
<span></span>
</div>
<div class="sidebar"></div>
The tags with the hamburger class will allow us to style the lines that make up the icon.
Step 2
Let’s handle the hamburger class.
.hamburger {
position: absolute;
top: 50px;
left: 35px;
cursor: pointer;
}
.hamburger span {
display: block;
width: 30px;
height: 0.3rem;
margin: 0.3rem 0;
background-color: #e91e63;
border-radius: 5px;
}
Step 3
Now it's our menu's turn!
.sidebar {
position: absolute;
top: 0;
left: 0;
width: 210px;
height: 100vh;
background-color: #e91e63;
transform: translateX(-210px);
transition: all .2s;
}
.sidebar.open {
transform: translateX(0);
}
Step 4
Let's detect the click on our icon using JavaScript.
const icon = document.querySelector('.hamburger');
const sidebar = document.querySelector('.sidebar');
let touchStart, touchEnd;
icon.addEventListener('click', () => {
sidebar.classList.add('open');
});
Step 5
All that's left is to capture the user's swipe movement.
sidebar.addEventListener('touchmove', e => {
touchEnd = e.targetTouches[0].clientX;
});
sidebar.addEventListener('touchend', e => {
if (touchStart - touchEnd > 100) {
sidebar.classList.remove('open');
}
});
Using the touchstart and touchmove events, we store the distance moved by the user's finger.
Step 6
Let's calculate the swipe distance to finalize the functionality.
sidebar.addEventListener('touchend', e => {
if (touchStart - touchEnd > 100) {
sidebar.classList.remove('open');
}
});
If our user has swiped more than 100px in distance, we remove the open class from our menu to close it.