ana bel
ana bel

Reputation: 187

Change the position of an image on mousemove

I want to change the position of the image when mouse move but the image doesn't change even if position is changed when I did console.log

var image = document.getElementById('img')

image.addEventListener('mousemove', function(e) {
  console.log(e.pageX * -1 / 12)
  var valueX = (e.pageX * -1 / 12);
  var valueY = (e.pageY * -1 / 12);
  image.style.backgroundPositionX = valueX + "px"
  image.style.backgroundPositionY = valueY + "px"
});
<header>

  <img id="img" src="https://placehold.it/100x100" alt="">

</header>

header {
    height: 100vh;
    width: 100%;
    position: absolute;
    overflow: hidden;
}

header img {
    width: 100%;
    height: 100%;
    position: absolute;
}

Upvotes: 0

Views: 5235

Answers (2)

Tigger
Tigger

Reputation: 9130

You almost had it. This sample code just fleshes things out a bit and moved some stuff to the CSS.

The key change was using a <div> instead of a <img>. As you were using backgroundPositionX and backgroundPositionY in the Javascript, these values are for the background image of an element and do not work with a <img>. Well, they can be used there too, but the src will hide the background unless you use a transparent image.

function mvImg(e) {
  var valueX = (e.pageX * -1 / 12);
  var valueY = (e.pageY * -1 / 12);
  this.style.backgroundPositionX = valueX + "px"
  this.style.backgroundPositionY = valueY + "px"
}
window.onload = function() {
  var im = document.getElementById("mv-img");
  if (im) {
    im.addEventListener("mousemove",mvImg,false);
  }  
}
#mv-img {
  width:100px;
  height:100px;
  background-image:url("https://via.placeholder.com/100/456");
  background-repeat: no-repeat;
  background-color: #192;
}
<div id="mv-img"></div>

Upvotes: 2

Rocky Sims
Rocky Sims

Reputation: 3598

You need to add style="position:absolute;" to your img.

Also, you need to change backgroundPositionX to left and backgroundPositionY to top.

I'm not entirely sure this is the behavior you're going for but following the above steps will cause the image to move when the mouse moves (provided the mouse is on the image).

Upvotes: 3

Related Questions