Gallery · 24 of 33

Directional Overlay

Overlay follows mouse entry direction

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="dir-overlay" id="dirOverlay">
  <img src="https://picsum.photos/id/160/800/600" alt="Direction">
  <div class="dir-content" id="dirContent"><span>Hello</span></div>
</div>

CSS

.dir-overlay {
  position: relative;
  width: 400px;
  aspect-ratio: 4 / 3;
  overflow: hidden;
  border-radius: 12px;
}

.dir-overlay img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.dir-content {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background: rgba(124, 92, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: system-ui, sans-serif;
  color: #fff;
  font-size: 1.5rem;
  font-weight: 600;
  transform: translate(0, 100%); /* off-screen by default; JS overrides */
  transition: transform 0.4s ease;
}

JavaScript

var overlay = document.getElementById('dirOverlay');
var content = document.getElementById('dirContent');

// 0 = top, 1 = right, 2 = bottom, 3 = left
function getDirection(e) {
  var rect = overlay.getBoundingClientRect();
  var x = e.clientX - rect.left - rect.width / 2;
  var y = e.clientY - rect.top - rect.height / 2;
  return Math.round((Math.atan2(y, x) * (180 / Math.PI) + 180) / 90 + 3) % 4;
}

var OFFSCREEN = [
  'translateY(-100%)', // top
  'translateX(100%)',  // right
  'translateY(100%)',  // bottom
  'translateX(-100%)'  // left
];

overlay.addEventListener('mouseenter', function (e) {
  // Jump (no transition) to the entry edge, then animate in
  content.style.transition = 'none';
  content.style.transform = OFFSCREEN[getDirection(e)];
  requestAnimationFrame(function () {
    content.style.transition = 'transform 0.4s ease';
    content.style.transform = 'translate(0, 0)';
  });
});

overlay.addEventListener('mouseleave', function (e) {
  content.style.transform = OFFSCREEN[getDirection(e)];
});