Believemy logo purple

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 the "swap" will make their experience on your site much easier, so you'll have a better user experience, which increases your chances of building loyalty. Let's find out how in this article!
Updated on December 9, 2024
Believemy logo

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!

Image

Step 1

Let's start with the HTML code.

HTML
<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.

CSS
.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!

CSS
.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.

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.

JAVASCRIPT
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.

JAVASCRIPT
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.

Category: Development
Believemy logo
Comments (0)

You need to be logged in to comment on this article: log in or sign up.

Try for Free

Whether you're scaling your startup, building your first website, or transitioning to a developer role, Believemy is your new home. Join us, grow, and let’s build your project together.

Believemy is with anyone