Moving Backgrounds With Mouse Position

Let's say you wanted to move the background-position on an element as you mouse over it to give the design a little pizzazz.

DevHoot
<div class="module" id="module"></div>

And you toss a background on it:

.module {
background-image: url(big-image.jpg);
}

You can adjust the background-position in JavaScript like this:

const el = document.querySelector("#module");

el.addEventListener("mousemove",(e) => {
  el.style.backgroundPositionX = -e.offsetX +"px";
  el.style.backgroundPositionY =-e.offsetY +"px";
});

Or, you could update CSS custom properties in the JavaScript instead:

const el = document.querySelector("#module");

el.addEventListener("mousemove", (e) => {
  el.style.setProperty('--x', -e.offsetX + "px");
  el.style.setProperty('--y', -e.offsetY + "px");
});
.module {
  --x: 0px;
  --y: 0px;
  background-image: url(large-image.jpg);
  background-position: var(--x) var(--y);
}

Here's an example that moves the background directly in JavaScript, but with a transition applied so it slides to the new position rather than jerking around the first time you enter:

Or, you could move an actual element instead (rather than the background-position). You'd do this if there is some kind of content or interactivity on the sliding element. Here's an example of that, which sets CSS custom properties again, but then actually moves the element via a CSS translate() and a calc() to temper the speed.

I'm sure there are loads of other ways to do this — a moving SVG viewBox, scripts controlling a canvas, webGL... who knows! If you have some fancier ways to handle this, link 'em up in the comments.

Subscribe below or here to receive new content whenever I publish. 👇

No new content, No new e-mail. Promise !!!