JavaScript Video Tutorial: Drag'n Drop Resizing


In this tutorial, I suggest you discover how to create a resizing system in JavaScript. The goal is to allow the user to resize the sidebar.

The style

For our structure we will use a grid with a CSS variable to control the width of the sidebar.


To control the sidebar, we will create an element that will serve as a selectable area (we will make this area voluntarily larger in order to facilitate the selection)

.resizer {
  position: absolute;
  top: 0;
  right: -10px;
  height: 100%;
  width: 20px;
  cursor: ew-resize;
  touch-action: none;
}

We will then use the nicknames element to define the visual aspect of our resizing cursor.

.resizer :: after {
  happy: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: coral;
  transform: scale (0);
  opacity: 0;
  transition: 0.3s;
}

.resizer: hover :: after {
  opacity: 1;
  transform: scaleX (0.2);
}

Mouse & Fingers

In order to manage the different devices we will use the PointerEvent type events which offers a common API to all the pointing devices.

// When we click on the element
element.addEventListener ("pointerdown", onPointerDown);

/ **
 * We start to listen to the movement of the cursor
 *
 * @param {PointerEvent} e
 ** /
function onPointerDown (e) {
  e.preventDefault ();
  document.addEventListener ("pointermove", onPointerMove);
  document.addEventListener ("pointerup", onPointerUp, {once: true});
}

/ **
 * When the cursor is moved, the width of the sidebar is updated
 *
 * @param {PointerEvent} e
 ** /
function onPointerMove (e) {
  e.preventDefault ();
  const sidebarWidth = e.pageX + "px";
  document.body.style.setProperty ("- sidebar", sidebarWidth);
}

/ **
 * When the cursor is released, we stop following the movement of the cursor
 *
 * @param {PointerEvent} e
 ** /
function onPointerUp (e) {
  document.removeEventListener ("pointermove", onPointerMove);
}

Limit the width

To limit the width of the sidebar we will rely on the CSS and the CSS function (clamp) (https://developer.mozilla.org/en-US/docs/Web/CSS/clamp ()) which will allow as a bonus to take the screen size into account.

.layout {
  --sidebarClamped: clamp (300px, var (- sidebar), 50vw);
  grid-template-columns: var (- sidebarClamped) 1fr;
}