Ethical38
Ethical38

Reputation: 77

How to make image move on hover with javascript?

So I have a background image but no html with tags but I want to make the background image move on hove with some type of javascript. But when I add the img tag into the html it covers everything else. Here is a live example I don't know that much javascript so I'm stuck.

body { background-image: url('images/bg_2880.jpg'); }

I need the javascript to move the image on the mouse hover like this js fiddle

Upvotes: 0

Views: 1446

Answers (1)

P Varga
P Varga

Reputation: 20229

This is called a parallax effect

Simple example:

addEventListener('mousemove', ev => {
  const force = 100;
  const dx = -ev.clientX / window.innerWidth * force;
  const dy = -ev.clientY / window.innerHeight * force;
  document.body.style.backgroundPositionX = dx + 'px';
  document.body.style.backgroundPositionY = dy + 'px';
});
body {
  background-image: url("http://placekitten.com/800/800");
}

Upvotes: 5

Related Questions